将ngFor索引绑定到Formcontrol Id

时间:2018-01-21 19:44:59

标签: angular ngfor formarray

当组件启动或添加新行时,我正在尝试将ngFor索引绑定到输入FormControlName

<tr *ngFor="let item of invForm.controls.tool.controls; let i= index" [formGroupName]="i" >
    <td>
        <mat-form-field floatLabel='never'>
            <input matInput type="number" style="text-align: right" formControlName="Id"  value="{{i+1}}" >
        </mat-form-field>
    </td>
</tr>

我做了整个例子,请看看id没有从输入中自动获取值。

https://stackblitz.com/edit/invoice-id

经过大量研究后,我找到了trackBy: trackByFn的简单解决方案。

<tr *ngFor="let item of invForm.controls.tool.controls; let i= index ;trackBy: trackByFn" [formGroupName]="i"  >

trackByFn(index, item) {

     item.value.Id = index+1
    return index; 
  } 

1 个答案:

答案 0 :(得分:0)

您的初始值设置不被视为更改/输入,因此不会更新FormControl上的值。如果您根据数组的长度确定ID,则可以将其传递给add函数并从html中删除value="{{i+1}}"

constructor(private formBuilder: FormBuilder) {
    this.invForm = this.formBuilder.group({
        tool: this.formBuilder.array([this.addEqp(1) ])
    });
}

addEqp(id: number) {
    const group =  this.formBuilder.group({
        Id: [id],
        qnt: [''],
        description: [''],
        price: [''],
        total: ['']
    });
    return group;
}

addEquip() {

    const control: FormArray = this.invForm.get(`tool`) as FormArray;
    control.push(this.addEqp(control.length + 1));
}

`