0

I can pass value in following way

template:

<td formArrayName="itemnameS">
<div *ngFor="let itemname of itemnameS.controls; let i=index">
<input [formControlName]="i" placeholder="Item Name">
</div>

component.ts:

form = new FormGroup({
    itemnameS: new FormArray([
      new FormControl('Gloves'),
      new FormControl('Gauze'),
      new FormControl('Needles'),
    ]),
    quantitieS: new FormArray([
      new FormControl(''),
    ]),
  });

Could please let me know how it is possible for drop down list as follows:

<select  formArrayName="itemnameS">
<option *ngFor="let itemname of itemnameS.controls; let i=index" >
                {{ ?? }}
</option>
</select>

Should look like as bellow:

enter image description here

1 Answer 1

1

You shouldn't create formArray :

form = new FormGroup({
    itemnameS: new FormArray([null]), // null to have at least one item initially
    quantitieS: new FormArray([
      new FormControl(''),
    ]),
  });

this.myItems = ['Gloves','Gauze','Needles'];

and then :

<div *ngFor="let control of form.get('itemnameS').controls ; let i = index" >
      <select  formControlName="control">
           <option *ngFor="let itemname of myItems; let i=index [value]='itemname' >
                {{ itemname }}
     </option>
</select>
  <button (click)="addNewOne()">Add</button>

        <button (click)="remove(i)">Remove</button>
</div>

Don't forget, a select is simply a user input and a user input could only have one controller, so one formControl must be assigned to it because eventually it's gonna have one value saved to your database.

and then if you wanted to implement the add new item functionality :

 addANewOne(){
     this.form.get('itemnameS').push(new FormControl())

  }

and for remove

 remove(index){
     this.form.get('itemnameS').removeAt(index)

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

8 Comments

Thanks Milad. You replyed so fast :). Your code is working fine. Just one thing I just forgot to ask. This is nested form. So json should look like ["Gloves","Gauze","Needles"] when submitting the form. Need your help. I just updated the picture above.
I think I just wrote your whole task hahaha:
Yes thanks :). But it is throughing error -> Can't bind to 'ngFor' since it isn't a known property of 'div'.
what ? You had used it before hahah
alright, I had forgotten to put let before control , that's it
|

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.