3

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.

1
  • what is the problem with this code?` Commented Nov 19, 2017 at 10:48

1 Answer 1

5

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

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

1 Comment

I spent all day with this issue. This worked like a charm. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.