Search code examples
angularangular-materialangular6angular-forms

Angular 6, how to update angular input field while looping?


I am trying to generate dynamic number of mat-form-field inside a html page.

I have the following data in component file:

data = [{
    'name': 'XYZ',
    'id': 1,
    'accNo': 123
  },
  {
    'name': 'ABC',
    'id': 2,
    'accNo': 456
  },
  {
    'name': 'PQR',
    'id': 3,
    'accNo': 567
  }
  ]

And in html, I am looping as follows:

<div class="flex-container">
    <div class="deposit-box" *ngFor="let c of data">
        <div>
            <mat-form-field appearance="outline">
                <mat-label>Name:</mat-label>
                <input matInput placeholder="Placeholder" 
        [(ngModel)]=c.name>
      </mat-form-field>
    </div>
  </div>
</div>

But I am facing problem in updating the value in input tag. only the first mat-form-field is getting the value.

Stackblitz: https://stackblitz.com/edit/angular-7a7add

Please help me.

Currently I am getting output as:

enter image description here


Solution

  • You need to use the ngFor inside the mat-form

     <mat-form-field appearance="outline">
        <div *ngFor="let c of data">  
            <mat-label>Name:</mat-label>
            <input placeholder="Placeholder" [(ngModel)]=c.name>
        </div>
      </mat-form-field>
    

    Demo