繁体   English   中英

Angular2自定义指令两种方式绑定

[英]Angular2 Custom Directive two way binding

我正在尝试编写一个自定义指令,如果用户在下拉菜单中选择“所有”选项,它将自动选择所有选项,而我已经能够选择所有选项来获得我的自定义指令,但这不会更新该模型。消耗组件。

自定义指令

@Directive({ selector: '[selectAll]' })
export class SelectAllDirective {
    private selectElement: any;
    private selectedItemsd:number[];

constructor(private el: ElementRef) {
    this.selectElement = el.nativeElement;
}

@HostListener('change')
onChange() {

    if (this.selectElement.options[0].selected) {
        for (let i = 0; i < this.selectElement.options.length; i++) {
            this.selectElement.options[i].selected = true;
        }
    }
}
}

和模板

  <select selectAll multiple
                                ngControl="shoreLocation"
                                #shoreLocation="ngModel"
                                id="shoreLocation"
                                [(ngModel)]="customTask.shoreLocations"
                                name="shoreLocation"
                                class="form-control multi-select"
                                required
                                style="height:150px">

我尝试创建一个@Input并在框式语法中使用banana来尝试更新模型,但我没有成功。

我能够使用@Output并发出一个事件,表明消费组件可以处理类似于https://toddmotto.com/component-events-event-emitter-output-angular-2的事件,但是如果我可以简单地更新自动建模。

我想知道是否可能? 或者,如果创建类似于http://plnkr.co/edit/ORBXA59mNeaidQCLa5x2?p=preview的自定义组件是更好的选择。

提前致谢

在Javascript中设置所选状态不会在select组件上发送“ changed”事件(可能是因为它是对子选项的直接访问,但不确定)。 尝试通过以下方式自己触发更改的事件:

if (this.selectElement.options[0].selected) {
    for (let i = 0; i < this.selectElement.options.length; i++) {
        this.selectElement.options[i].selected = true;
    }
    //These are the two new lines
    let changeEvent = new Event("change", {"bubbles":true, "cancelable": false});
    this.selectElement.dispatchEvent(changeEvent);
}

并查看是否触发ngModel进行更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM