itismelito
itismelito

Reputation: 255

Access object properties in a FormArray and update the values in Angular 4

I want to access the object properties and bind values from a form. So far i have tried different options but no success. This is what i have so far, i have simplified the code below:

The FormGroup:

this.form = this.fb.group({
  ingredients: new FormArray([this.fb.group({name: 'Pasta', price: ''})])
})

The View code:

<div formArrayName="ingredients">
  <ion-item *ngFor="let ingredient of form['controls'].ingredients['controls']; let i = index" padding-bottom>
    <div [formGroupName]="i">
        <ion-input formControlName="price" type="number"></ion-input>
    </div>
  </ion-item>
</div>

The code above is simplified for this question purpose, the scenario is different but at the end ends up like this where i want to update the price value inside the object. I have seen a lot of ways of doing it while i did my research but nothing seems to work for me.

Upvotes: 3

Views: 2602

Answers (1)

crystalthinker
crystalthinker

Reputation: 1182

Try this :-

  <form [formGroup]="form">
  <div formArrayName="ingredients">
    <div *ngFor="let ingredient of form['controls'].ingredients['controls']; let i = index" [formGroupName]="i">
    <input formControlName="price" type="number"/>
    </div>
    </div>
  </form>

and ts :-

form: FormGroup;

  constructor(builder: FormBuilder) {
    this.form = builder.group({
      ingredients: new FormArray([
        builder.group({
            name: 'Pasta',
            price: '',
        })
      ]);
    })
  }

Please check this plunker for the solution. http://plnkr.co/edit/it3VW8wvYfYmk2Ox6M60?p=preview

Upvotes: 4

Related Questions