本文介绍了mdOption 的 (onSelectChange) 输出总是通过列表中的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Angular 4 (4.3.4) 中使用 Angular Material,我需要挂钩选择事件以清除输入并将对象存储在单独的列表中.但是有一个问题:onSelectChange 输出总是获取第一项作为参数!怎么回事?
这是我的模板:
<md-选项*ngFor="let role of roles | acrole: roleField.value | slice:0:4; let i=index;"[值]="角色"(onSelectionChange)="AddRole(role)" ><div class="label">{{角色.标签}}
</md-option></md-自动完成>
这是我的 AddRole 函数:
AddRole(角色:角色){//角色始终是列表中的第一个角色,无论我单击哪个选项.this.selectedList.push(角色)}
解决方案
通过 onSelectionChange
事件,可以区分项目是被选中还是未选中.您需要将 $event
传递给目标方法以区分这两种情况.
为了使更改生效,您需要进行以下更改:
在您的组件 html 中:
<md-选项*ngFor="let role of roles | acrole: roleField.value | slice:0:4; let i=index;"[值]="角色"(onSelectionChange)="AddRole($event, role)"><div class="label">{{角色.标签}}
</md-option></md-自动完成>
... 并在您的 component.ts 中,将方法更改为以下内容:
AddRole(event: MdOptionSelectionChange, role: Role) {如果(event.source.selected){this.selectedList.push(角色);}}
这是一个PLUNKER DEMO材料文档示例.文档需要更清楚地说明这些更改.
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:
<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>
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.
这篇关于mdOption 的 (onSelectChange) 输出总是通过列表中的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!