【问题标题】:patch value issue when update the form更新表单时的补丁值问题
【发布时间】:2020-08-13 08:33:55
【问题描述】:

更新表单时,我使用补丁值在表单中显示创建的数据,我能够在所有表单字段中显示创建的数据,但一个字段除外。我还使用 setValue 来显示该特定的数据字段,但它不起作用,任何人都可以提供解决方案。 这是代码 ts

 public addMaterialForm = this.fb.group({

    barcodes:[],
    labelSpecs:[],
    labelSize: [''],

  })

 ngOnInit() { 
    this.receiptSrv.currentSharedMaterial.distinctUntilChanged().subscribe(data => {
      if (data) {
        this.addMaterialForm.patchValue(data);
        this.editMode =true;
      }
    });
  }  

html

<!-- Label Size -->
<div fxLayout="row">
    <mat-form-field>
    <mat-label>Barcodes Size</mat-label>
    <mat-select formControlName="labelSize" required>
        <mat-option *ngFor="let barcode of barcodes" [value]="barcode">
        Barcodes Size- {{barcode.height}} X {{barcode.width}}
        </mat-option>
    </mat-select>
    <mat-error *ngFor="let labelSizeMsg of materialInfoValMsg.labelSize">
        <mat-error class="error-message" *ngIf="addMaterialForm.get('labelSize').hasError(labelSizeMsg.type) &&
            (addMaterialForm.get('labelSize').dirty || addMaterialForm.get('labelSize').touched)">
        {{labelSizeMsg.message}}
        </mat-error>
        </mat-error>
    </mat-form-field>
</div>

这是来自后端的响应

labelSize: "{"createdAt":null,"modifiedAt":null,"createdBy":null,"modifiedBy":null,"id":"641a55d1-1026-4093-b339-02174b09891a","height":1,"width":1}"

我需要在 barcodeSize-1X1 这样的表单的 barcodeSize 字段中显示宽度和高度。

【问题讨论】:

    标签: html angular typescript angular-material


    【解决方案1】:

    阅读此文档angular-reactive-forms 我看到了以下内容

    patchValue() 方法将更新应用于模型结构。 PatchValue() 只更新表单模型定义的属性。

    所以,您的 addMaterialForm 是具有这种结构的对象 { barcodes: null, labelSpecs: null, labelSize: null }

    并且您正在尝试使用具有此结构的对象对其进行更新 { "createdAt": null, "modifiedAt": null, "createdBy": null, "modifiedBy": null, "id": "641a55d1-1026-4093-b339-02174b09891a", "height": 1, "width": 1 } 它不起作用,因为它不知道应该设置表单的哪个属性。

    您的 API 应返回如下内容: { "labelSize": { "createdAt": null, "modifiedAt": null, "createdBy": null, "modifiedBy": null, "id": "641a55d1-1026-4093-b339-02174b09891a", "height": 1, "width": 1 } }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      相关资源
      最近更新 更多