【问题标题】:Property 'Rows' comes from an index signature, so it must be accessed with ['Rows']属性 \'Rows\' 来自索引签名,因此必须使用 [\'Rows\'] 访问它
【发布时间】:2022-12-13 09:48:44
【问题描述】:

我正在尝试使用 FormArray 但出现错误:

属性“Rows”来自索引签名,因此必须使用 ['Rows'] 访问它。

*ngFor="let itemrow of invoiceForm.controls.Rows.controls"

HTML 文件:

<form [formGroup]="invoiceForm">
    <table border=1>
        <thead>
            <th>Id</th>
            <th>Name</th>
            <th>Action</th>
        </thead>
        <tbody formArrayName="Rows">
            <tr *ngFor="let itemrow of invoiceForm.controls.Rows.controls; let i=index;let l=last"
                [formGroupName]="i">
                <td>{{i+1}}</td>
                <td>
                <mat-form-field  appearance="fill">
                <mat-label>Input</mat-label>
                <input matInput formControlName="name" class="form-control">
            </mat-form-field>
        </td>
                <td>
                    <button *ngIf="invoiceForm.controls.Rows.controls.length > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>
<button type="button" (click)="addNewRow()" class="btn btn-primary">Add new Row</button>
<br/>
<br/>

TS文件:

public invoiceForm!: FormGroup;
constructor(private _fb: FormBuilder) {}
ngOnInit() {
  this.invoiceForm = this._fb.group({
    Rows: this._fb.array([this.initRows()])
  });
}

get formArr() {
  return this.invoiceForm.get("Rows") as FormArray;
}

initRows() {
  return this._fb.group({
    name: [""]
  });
}

addNewRow() {
  this.formArr.push(this.initRows());
}

deleteRow(index: number) {
  this.formArr.removeAt(index);
}

【问题讨论】:

    标签: angular typescript angular-reactive-forms angular12 formarray


    【解决方案1】:

    由于您为 formArr FormArray 实施了 getter,

    get formArr() {
      return this.invoiceForm.get("Rows") as FormArray;
    }
    

    您可以按如下方式重用吸气剂(在 HTML 中):

    <tr *ngFor="let itemrow of formArr.controls; let i=index;let l=last"
                    [formGroupName]="i">
      ...
    </tr>
    
    <button *ngIf="formArr.controls.length > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete</button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2014-04-09
      相关资源
      最近更新 更多