我正在使用Angular的反應表單,並希望將一個CSS樣式應用於FormArray內的控件,具體取決於控件的無效屬性的值。我提出了以下方法,但我認爲ngClass屬性中的表達式太長且很複雜。是否有更簡潔的方式來訪問FormArray中的控件的無效屬性?在表單陣列中訪問模板內控件的驗證器狀態
模板:
<form [formGroup]="myForm" class="form-horizontal">
<div class="form-group" [ngClass]="{'has-error': myForm.controls.name.invalid }">
<label class="control-label">Name</label>
<input formControlName="name" type="text" class="form-control" />
</div>
<div formArrayName="array1">
<div *ngFor="let f of array1_FA.controls; let i = index" [formGroupName]="i">
<div>
<div class="form-group"
[ngClass]="{'has-error': myForm.controls.array1.at(i).controls.question.invalid}">
<label class="control-label">Question #{{i+1}}</label>
<input formControlName="question" class="form-control" type="text" />
</div>
<div class="form-group"
[ngClass]="{'has-error': myForm.controls.array1.at(i).controls.response.invalid}">
<label class="control-label">Answer #{{i+1}}</label>
<input formControlName="response" class="form-control" type="text" />
</div>
</div>
</div>
</div>
</form>
組件:
import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'form-array-validation',
templateUrl: './form-array-validation.component.html'
})
export class FormArrayValidationComponent {
myForm: FormGroup;
questions = ['Q1', 'Q2', 'Q3', 'Q4'];
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.myForm = this.fb.group({
name: ['Name1', Validators.required],
array1: this.fb.array(this.questions.map(val => this.fb.group({
question: [val, Validators.required],
response: [null, Validators.required]
})))
});
}
get array1_FA(): FormArray {
return this.myForm.get('array1') as FormArray;
};
}
你有沒有看不用彷徨?這提供了一個快捷的語法:https://angular.io/guide/reactive-forms#inspect-formcontrol-properties – DeborahK
我的確認爲.get使它更易讀,但仍然非常接近。 (i).get('question')。invalid' – EricAZ