我有在FormBuilder的帮助下构建的Angular表单。
表单包含一个表单数组,它具有用户想要的任意数量的字段。我已经为字段设置了验证器
this.fb.array([this.fb.control('', Validators.required)])
对于每个新push
验证器都是相同的。
问题是我不知道如何访问特定字段的isValid
属性,因为它们通过[formControlName]="index"
与FormControl
绑定。
我尝试过这样做,但它似乎不起作用
<div *ngIf="array.at(index).invalid" class="alert alert-danger p-2">
</div>
其中array
是从父级传递的formArray.controls
。
更新 #1
有一个案例 https://stackblitz.com/edit/angular-7ppkoh
我真的不认为这在模板上完全可行。这是因为若要在模板中访问 FormArray 控件的状态,必须访问this.formGroup.get('features').controls[i].invalid
。但是由于get
返回了一个类型AbstractControl
的实例,您将无法访问其上的controls
数组。为此,您必须将从this.formGroup.get('features')
返回的任何内容类型转换为FormArray
。而且我真的认为这在模板上是不可能的。
您必须在类中创建一个方法,该方法将基于索引返回控件的有效性。
因此,如果我们继续参考您的堆栈闪电战,例如,方法如下:
<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()"
OR[style.styleName]="methodName()"
(中调用方法就性能而言是非常昂贵的。
因此,您应该使用以下方法进行操作:
{{ formGroup.controls['features'].controls[index].invalid }}
而不是:
{{ getValidity(index) }}
这是您的参考的更新工作示例 StackBlitz。
如果您想了解更多信息,我强烈建议您查看此线程:
角度性能:DOM 事件导致不必要的函数调用
希望这对:)有所帮助
我在角度 8 中有这个例子。
执行此操作时,在模板中。
<ng-container formArrayName="calibers">
<ng-container *ngFor="let item of qualityForm.get('calibers')['controls']; let index = index" [formGroupName]="index.toString()">
<ion-item>
<ion-label position="floating">{{ getCaliberName(item) }}</ion-label>
<ion-input formControlName="percentage" placeholder="Input Percentage" type="number" clearInput></ion-input>
<ng-container *ngIf="item.get('percentage').hasError('required')">
<span class="errorMsg">Input Percentage</span>
</ng-container>
<ng-container *ngIf="item.get('percentage').hasError('max')">
<span class="errorMsg">Percentage cannot be greater than 100</span>
</ng-container>
</ion-item>
</ng-container>
</ng-container>
ngFor 中的该项对象将允许您访问表单控件。 获取数组表单错误所需要做的就是item.get('percentage').hasError('required')
在 ngFor 语句中,您正在定义变量 "feature" 以用于表单数组的每个控件。
*ngFor="let feature of features.controls; let index = index; let last = last"
可以使用该变量获取该控件的无效状态。
feature.invalid
这是堆栈闪电战
此外
使用反应式表单时,HTML 中不需要必需的属性。
所以这个
<input type="text" class="form-control px-2 col" [formControlName]="index" title="feature" required>
可以
<input type="text" class="form-control px-2 col" [formControlName]="index" title="feature">
您应该使用表单控件来敏锐地实现这一点。
<div *ngIf="formGroup.get('features').controls[i].controls.index.invalid && (formGroup.get('features').controls[i].controls.index.dirty || formGroup.get('features').controls[i].controls.index.touched)" class="text-center error">
<p [hidden]="!formGroup.get('features').controls[i].controls.index.errors.required">Index is required.</p>
</div>
如上所述,使用
feature.invalid
来自features.controls
允许您一次验证该控件中的所有元素。
但是,如果要验证特定元素,可以遵循以下代码:
> feature.controls.controlname.invalid
注意:我使用的是功能而不是功能
FormGroup 类有一个 get 方法,该方法返回给定键的抽象控件。在窗体控件名称中使用的那个。
这里是两个 API 文档的链接:
AbstractControl
FormGroup
<form [formGroup]="form">
<input formControlName="name" type="text" />
<div *ngIf="form.get('name').invalid">
<p><Message you like to show/p>
</div>
</form>
使用 formArray 创建表单。
createForm() {
this.studentForm = this.fb.group({
name: [],
id: [],
hobbies: this.fb.array([])
})
}
addHobbies() {
const control = new FormControl(null, [Validators.required]);
(<FormArray>this.studentForm.get('hobbies')).push(control);
}
向用户打印错误消息
<form [formGroup]="studentForm" (submit)="saveStudent()">
<input type="text" id="id" name="id" formControlName="id">
<input type="text" id="name" name="name" formControlName="name">
<div formArrayName="hobbies">
<label>Hobbies</label>
<button type="button" (click)="addHobbies()">Add Hobbies</button>
<div *ngFor="let formControl of studentForm.get('hobbies')['controls']; let i = index">
<input type="text" [formControlName]="i">
<div *ngIf="!studentForm.get('hobbies')['controls'][i].valid &&
studentForm.get('hobbies')['controls'][i].errors?.required">
<p>This field is required</p>
</div>
</div>
</div>
<button type="submit">Submit Student</button>
</form>