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()"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With