How to give the value of an array element for a value in the formbuilder group?

620 Views Asked by At

I want to populate the dropdown in angular reactive form through the data obtained from endpoint. It is created as a FormArray as follows. userDetailsData is the data object which is store the data obtained through the backend.

this.userDetailsData.user_context.forEach(async data => {
       const userContext = this.createJobForm.get('user_context') as FormArray;
        this.parent_id = this.parentList.find(parent => parent.parent_name === data.parent_name)?.id;
        this.toyList = this.parentList.filter(toy => toy.id === this.parent_id).flatMap(item => item.toys);
        await this.getUsersList();
        this.userIdentifier = this.userList.find(user => user.name === data.username)?.identifier;

        userContext.insert(0, this.formBuilder.group({
            parent_id: [this.parent_id, [Validators.required]],
            user_identifier: [this.userIdentifier],
            dynamic_users: [this.isUserAvailble ? true : false],
            toy_id: [this.toyList[0].id]  // Beacuse of this, only the first toy id in the array is always set.
        }));
    }); 
[
    {
        "id": "A1450D375-7257-4555F5-BA30-DF246ED6E",
        "type": "toy",
        "parent_name": "admin",
        "toy_name": "Test_Toy12"
    },
    {
        "id": "6A0EC-185A-DF-80A-FD7BB298CE2gDERTF",
        "type": "toy",
        "parent_name": "admin",
         "toy_name": "Test_Toy56"
    }
]

The toyList returns an array like this. How to dynamically set the id as the value of the toy_id of the formBuilder.group?

1

There are 1 best solutions below

2
Nehal On

Write some html that will create a dropdown list for the user. Then you can attach the formControlName to the dropdown, that will bind toy_id to the selected toy.

Here's a simplified example of the above:

    <form [formGroup]="form">
      <div *ngIf="f.length > 0">
        <div *ngFor="let context of f.controls; let i = index">
          <div [formGroup]="context">
            <ng-container>
              <select name="cars" id="cars" formControlName="toy_id" [(ngModel)]="selectedToyId">
                <option *ngFor="let item of toyList" [value]="item.id">{{item.toy_name}}</option>
              </select>
            </ng-container>
          </div>
        </div>
      </div>
    </form>

Stackblitz Demo