小编Eri*_*cAZ的帖子

在FormArray中的控件的模板内部访问验证器的状态

我正在使用Angular的反应形式,并希望根据控件的invalid属性的值将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>
Run Code Online (Sandbox Code Playgroud)

零件:

import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'form-array-validation', …
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular-reactive-forms

4
推荐指数
1
解决办法
1438
查看次数