I'm using Angular Material for Angular 4 (4.3.4) and I need to hook into the selection event to clear the input and store the object in a separate list. But there's a problem: the onSelectChange output ALWAYS gets the first item as the parameter! What's going on?
Here's my template:
<md-autocomplete [displayWith]="displayRole" #auto="mdAutocomplete">
<md-option
*ngFor="let role of roles | acrole: roleField.value | slice:0:4; let i=index;"
[value]="role"
(onSelectionChange)="AddRole(role)" >
<div class="label">
{{role.label}}
</div>
</md-option>
</md-autocomplete>
And here's my AddRole function:
AddRole(role: Role)
{
// role is always the first role in the list, no matter which option I clicked on.
this.selectedList.push(role)
}
With onSelectionChange
event, it is possible to differentiate when the item is selected or unselected. You need to pass an $event
to the target method in order to differentiate between the two cases.
Here are the changes you need to make in order to make your changes work:
In your component html:
<md-autocomplete [displayWith]="displayRole" #auto="mdAutocomplete">
<md-option
*ngFor="let role of roles | acrole: roleField.value | slice:0:4; let i=index;"
[value]="role"
(onSelectionChange)="AddRole($event, role)">
<div class="label">
{{role.label}}
</div>
</md-option>
</md-autocomplete>
... and in your component.ts, change the method to following:
AddRole(event: MdOptionSelectionChange, role: Role) {
if (event.source.selected) {
this.selectedList.push(role);
}
}
Here is a PLUNKER DEMO based on the Material documentation example. The documentation needs to be a bit more clear about these changes.