mdOption的(onSelectChange)输出始终通过列表中的第一项 [英] (onSelectChange) output for mdOption ALWAYS gets passed first item in list

查看:185
本文介绍了mdOption的(onSelectChange)输出始终通过列表中的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 4(4.3.4)的Angular Material,我需要加入选择事件以清除输入并将对象存储在单独的列表中.但是有一个问题:onSelectChange输出始终将第一项作为参数!发生了什么事?

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?

这是我的模板:

<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>

这是我的AddRole函数:

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) 
}

推荐答案

使用onSelectionChange事件,可以区分选择还是不选择该项目.您需要将$event传递给目标方法,以区分这两种情况.

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:

在您的组件html中:

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>

...,然后在您的component.ts中,将方法更改为以下内容:

... 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.

这篇关于mdOption的(onSelectChange)输出始终通过列表中的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆