如果 Angular 中的行中缺少一个字段,则禁用添加行

Disable Add Row If One Field is Missing in Row in Angular

如果行中的一个字段尚未输入或选择,我如何禁用 "add row button"?还有,当该行只剩下一个时,我如何禁用 "remove button" ?这是我的 stackblitz 代码 link

https://stackblitz.com/edit/form-array-patch-ztxnvy?file=app%2Fapp.component.ts

TS

initGroup() {
    let rows = this.addForm.get('rows') as FormArray;
    rows.push(this.fb.group({
      ingredient_id: ['', Validators.required],
      unit_price: new FormControl({ value: '', disabled: true }, Validators.required),
      quantity: ['', Validators.required],
    }))
  }

How can i disable the "add row button" IF one field in the row is not yet inputted or selected?

您可以在 addForm

上使用无效的 属性
<button [disabled]="addForm.invalid">Add Row</button>

这会在表单无效时禁用添加行按钮。使用您设置的验证器,当任何行中的任何输入未填写时。


And also how can i disable the "remove button" when the row is only one left?

您可以检查表单数组的长度。如果它等于 1 则禁用删除按钮

<button [disabled]="addForm.controls.rows.controls.length === 1">Remove</button>

How can i disable the whole field in the single row. After i inputted the values. Like when you click the add row. The previous row will not be anymore be edited?

您可以通过编程方式检查该行是否是表单数组中的最后一行。如果是,则启用这些字段,否则禁用这些字段。

let rows = this.addForm.get('rows');
rows.controls.forEach((control, index) => {
    // if row is not last row disable fields, else enable fields
    if(index !== rows.controls.length - 1){
        control.controls['ingredient_id'].disable();
        control.controls['quantity'].disable();
    }else{
        control.controls['ingredient_id'].enable();
        control.controls['quantity'].enable();
  }
})

这是您的 stackblitz 演示的一个分支。