Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send the parent object for a property selected in the Angular Material Autocomplete?

I'm working with Angular 4 Material, and specifically the Autocomplete component.

My list of options filteredHomeTeams is of type Observable< Team[ ] > and I'm building the dropdown and the selection using a property of such object called teamName

Here is the HTML:

<mat-form-field class="example-full-width">
            <input type="text" matInput placeholder="Local" [formControl]="HomeTeamCtrl" [matAutocomplete]="homeAuto">
            <mat-autocomplete #homeAuto="matAutocomplete" (optionSelected)="setHomeTeam()">
                    <mat-option *ngFor="let team of filteredHomeTeams | async" [value]="team.teamName" >
                        {{ team.teamName }}
                    </mat-option>
            </mat-autocomplete>
</mat-form-field>

As you can see I have an event called optionSelected that calls a method setHomeTeam()

My Team class is:

export class Team {
    teamName: string;
    teamSelfRef: string;
}

What I need to do, and this is probably very basic for experienced angular programers is:

I selected team.teamName in the dropdown, and I have team.teamName in the input field. How can I pass the team.teamSelfRef from the same object as a parameter to "setHomeTeam()"?

I need to build and select the object based on the name, but I need to trigger logic with a different property.

It would also work if I can pass the entire object as parameter to the method "setHomeTeam()"

like image 490
Matias Diez Avatar asked Jan 31 '26 05:01

Matias Diez


1 Answers

Alic W is correct, which is btw explained in the docs: Setting separate control and display values The addition to Alic W's code is how to get the value you desire.

So as Alic W said, you bind the object with value:

[value]="team"

and add the displayWith:

<mat-autocomplete #homeAuto="matAutocomplete" 
                  [displayWith]="displayFn"  
                  (optionSelected)="setHomeTeam()">

The displayFn:

displayFn(team: Team): string {
    return team? team.teamName: team;
}

and then you can access the complete object (including the teamSelfRef) property from your form control HomeTeamCtrl:

setHomeTeam() {
  console.log(this.myControl.value.teamSelfRef)
}

Here's a demo from the docs and their variables: https://plnkr.co/edit/zlKFIytpI6pokfZi3ofm?p=preview

like image 185
AT82 Avatar answered Feb 02 '26 22:02

AT82