我真的不认为这完全可以在模板上实现。这是因为要访问模板中 FormArray 控件的状态,您必须访问 this.formGroup.get('features').controls[i].invalid。但是由于get 返回一个AbstractControl 类型的实例,您将无法访问它上面的controls 数组。为此,您必须将从this.formGroup.get('features') 返回的任何内容类型转换为FormArray。而且我真的不认为这在模板上是可能的。
您必须在您的类中创建一个方法,该方法将根据索引返回控件的有效性。
因此,如果我们继续参考您的 stackblitz,例如,方法如下:
<form [formGroup]="formGroup">
<div formArrayName="features">
<div
class="row no-gutters form-group"
*ngFor="let feature of features.controls; let index = index; let last = last">
<input
type="text"
class="form-control px-2 col"
[formControlName]="index"
title="feature"
required>
IS Invalid - {{ getValidity(index) }}
<div class="col-3 col-md-2 row no-gutters">
<button
class="col btn btn-outline-danger"
(click)="removeFeature(index)">
-
</button>
<button
class="col btn btn-success"
*ngIf="last"
(click)="addFeature()">
+
</button>
</div>
</div>
</div>
</form>
在你的课堂上:
import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(
private fb: FormBuilder,
) {}
formGroup = this.fb.group({
features: this.fb.array([this.fb.control('', Validators.required)])
});
get features(): FormArray {
return this.formGroup.get('features') as FormArray;
}
addFeature(): void {
this.features.push(this.fb.control('', Validators.required));
}
getValidity(i) {
return (<FormArray>this.formGroup.get('features')).controls[i].invalid;
}
removeFeature(index): void {
this.features.removeAt(index);
console.log(this.features);
}
}
更新
几个月前,我意识到在其中一种数据绑定语法中调用方法(即字符串插值 - {{ ... }}、属性绑定 - [propertyName]="methodName()" 或属性绑定 - [class.class-name]="methodName()" 或 [style.styleName]="methodName()")是就性能而言,代价极高。
所以,你应该这样做:
{{ formGroup.controls['features'].controls[index].invalid }}
代替:
{{ getValidity(index) }}
这是一个更新的 Working Sample StackBlitz 供您参考。
如果您想了解更多信息,我强烈建议您查看此线程:
Angular Performance: DOM Event causes unnecessary function calls
希望这会有所帮助:)