Reputation: 27
I am not able to apply validators on all the input filed generated dynamically. This works for only first input field.
I tried using linkSubmitForm.controls.links.<controls-I-valid>
but it is not returning anything.
Help please!!
My html code:
<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>
My ts code:
@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)
}
Upvotes: 0
Views: 672
Reputation: 5021
You have to keep the Validators.required
in the control itself. And then you can get each control status like below
Template file
<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 File
this.testForm = this.fb.group({
names: this.fb.array([
this.fb.control('', [Validators.required])
])
});
Working Stackblitz
Upvotes: 1