我无法对所有动态生成的输入字段应用验证器。这仅适用于第一个输入字段。
我尝试使用linkSubmitForm.controls.links.<controls-I-valid>
,但未返回任何内容。
请帮忙!
我的html代码:
<form [formGroup]="linkSubmitForm" (ngSubmit)="onSubmit()"></form>
<input #myInput *ngFor="let link of links.controls; let i=index" class="form-control" type="file" [formControlName]="i" required>
<div *ngIf="linkSubmitForm.controls.links.invalid &&
linkSubmitForm.controls.links.touched" >
This field is required
</div>
<button type="submit">Submit</button>
</form>
我的ts代码:
@ViewChild('myInput') inputEl: ElementRef;
@ViewChildren('myInput', { read: ElementRef }) many_links_el: QueryList<ElementRef>
linkSubmitForm = this.formBuilder.group({
links: this.formBuilder.array([
this.formBuilder.control(''),
Validators.required,
]),
});
get links() { return this.linkSubmitForm.get('links') as FormArray; }
ngOnInit() { `enter code here` while(--3) this.links.push(this.formBuilder.control('', Validators.required) }
onSubmit() {
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
//var formData = new FormData();
this.file = inputEl.files;
console.log('file object', this.file);
this.many_links_el.toArray();
let files=[];
this.many_links_el.forEach((e)=>{
let inputElement=e.nativeElement;
if(inputElement.files.length){
files.push(inputElement.files[0])
}
})
console.log(files)
}
答案 0 :(得分:1)
您必须将Validators.required
保留在控件本身中。然后您可以获取如下所示的每个控件状态
模板文件
<form [formGroup]='testForm'>
<div formArrayName="names">
<h3>Names</h3> <button (click)="addName()">Add Alias</button>
<div *ngFor="let name of names.controls; let i=index">
<label>
Name:
<input type="text" [formControlName]="i">
<div *ngIf="names.controls[i].status === 'INVALID' &&
names.controls[i].touched">
Above field is required
</div>
</label>
</div>
</div>
</form>
TS文件
this.testForm = this.fb.group({
names: this.fb.array([
this.fb.control('', [Validators.required])
])
});