0

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)
}
1
  • Hi Vinay, the answer gave to you helped fixing your issue? Commented Oct 22, 2019 at 5:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.