Angular: Assign value to nested attribute

363 views Asked by At

I am a beginner in Angular to apologies if this is something trivial. I am creating the frontend for an API which has a structure like this:

{ "eventTitle": "", "partnerType": "", "city": "", "activity": { "name": "" }, "business_id": "", "organizationName": "", "collegeActivity": "", "name": "", "dateOfEvent": null, "musicContest": null, "collegeName": null, "budget": null }

Now I have this nested formbuilder object, and I want the values selected to be added as an array of objects somewhat like this:

"activity": [{"name": "record_labels"}, {"name": "gigs"}]

Here is my component.ts file

leadForm = this._formBuilder.group(
    {
      eventTitle: [""],
...
      activity: this._formBuilder.group({
        name: [""]
      }),
...   


    }
  ) 

here is the html template

 <div class="form-group">
        <!--activity-->
        <label for="activity">Select Activity</label>
        <mat-select multiple class="form-control" id="activitySelect" name="activity" (change) = "onActivity()" formControlName="activity">
            <ng-container>
                <mat-option selected disabled value="">Select Activity</mat-option>
                <mat-option *ngFor = "let activity of activities" [value]= "activity.json_name">{{activity.name}}</mat-option>
            </ng-container>            
        </mat-select>
    </div>

here is what the activities array looks like-

 activities = [
    {
      id: 0, name: "Record Deals", json_name: "record_deal"      
    },
    {
      id: 1, name: "Artist Management", json_name: "artist_management"
    },
]
1

There are 1 answers

2
Caio Oliveira On

Prepare the activities arrays to look like what you expect using a map first.

this.activities = this.activities.map(a=>{return {name: a.json_name} })

Then on the option value, just use the activity itself

                <mat-option *ngFor = "let activity of activities" [value]= "activity">{{activity.name}}</mat-option>