Search code examples
angularangular8angular-reactive-formsngfor

Is there way to use angular directives(*ngfor) in angular reactive forms?


When submitting the form, is there a way to retain all the data without replacing with a same data(marks) in the Angular Reactive forms that change with Angular Directives? I tried bellow code but, I couldn't find out way to get all "marks" inputs.

    <div *ngFor="let item of stuData">
      <label>{{item.name}}</label>
      <input type="number" min="0" max="100" placeholder="Marks" formControlName="marks">
    </div>

Solution

  • You can probably arrange something with dynamics form groups like this:

    https://www.bitovi.com/blog/managing-nested-and-dynamic-forms-in-angular

    <ng-container *ngFor="let userFormGroup of usersForm.controls.users.controls; let i = index">
      <div [formGroup]="userFormGroup">
        {{stuData[i]}}
         <label>
          Mark
          <input type="text" formControlName="marks">
        </label>
      </div>
    </ng-container>
    

    And in the .ts

    let fgArray: FormGroup[];
    
    fgArray.forEach(element => {
      this.fb.group({
        mark: ['', null],
      });
    })
    
    this.usersForm = this.fb.group({
          users: this.fb.array(fgArray)
    })