我尝试用这种方式为一些动态输入添加验证,但没有成功,我非常感谢您的帮助。
这是HTML,它用ts中建立的动态输入定义表单,如果输入未完成,则应激活mat错误,指示需要该字段。
HTML
<div formArrayName="dynamic_fields" >
<div *ngFor="let field of dynamicFields; let i = index">
<mat-form-field>
<input
matInput
[formControlName]="i"
[type]="field.type"
[placeholder]="field.name"
/>
</mat-form-field>
<mat-error *ngIf="i.hasError('required')">
this field is required
</mat-error>
</div>
</div>
这是我定义表单初始化并进行验证的ts,因此所有以前定义的字段都是必需的。
ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-dynamicForm',
templateUrl: './dynamic-form.component.html',
styleUrls: ['./dynamic-form.component.scss'],
})
export class DynamicFormComponent implements OnInit {
public dynamicFields: any;
public form: FormGroup;
public fields: any = [
{
name: 'name',
type: 'text'
},
{
name: 'atributte',
type: 'text'
},
{
name: 'grade',
type: 'number'
}
]
constructor( private fb: FormBuilder ) { }
ngOnInit() {
this.start();
}
start() {
this.form = this.fb.group({})
this.dynamicFields = this.fields
console.log(this.dynamicFields)
if (this.dynamicFields) {
this.form.addControl(
'dynamic_fields',
this.fb.array(
this.dynamicFields?.map(x => {
this.fb.control(x.name, Validators.required);
}, {}) || []
)
);
}
}
}
将完整的formArray
添加到addControl
方法不起作用。您可以先创建dynamic_fields
表单数组字段。
public form = this.fb.group({
dynamic_fields: this.fb.array([]),
});
然后一次将dynamicFields
到dynamic_fields
的每个元素从阵列推到on。
start() {
this.dynamicFields = this.fields;
if (this.dynamicFields) {
const customFields = this.form.get('dynamic_fields') as FormArray;
this.dynamicFields?.forEach((x: any) => {
customFields.push(this.fb.control(x.name, [Validators.required]));
}, {});
}
}
HTML
<div [formGroup]="form">
<div formArrayName="dynamic_fields">
<div *ngFor="let field of dynamicFields; let i = index">
<mat-form-field>
<input
matInput
[formControlName]="i"
[type]="field.type"
[placeholder]="field.name"
/>
<mat-error *ngIf="form.get(['dynamic_fields', i])?.hasError('required')">
this field is required
</mat-error>
</mat-form-field>
</div>
</div>
</div>
工作堆栈闪电战