【问题标题】:Angular2 Custom Directive two way bindingAngular2自定义指令双向绑定
【发布时间】:2016-08-23 11:40:04
【问题描述】:

我正在尝试编写一个自定义指令,如果用户在下拉菜单中选择“全部”选项,它会自动选择所有选项我能够让我的自定义指令选择所有选项,但这不会更新消费组件上的模型。

自定义指令

@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 并使用 box 语法中的香蕉来尝试更新模型,但没有成功。

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

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

提前致谢

【问题讨论】:

    标签: javascript angular angularjs-directive


    【解决方案1】:

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

    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 进行更新。

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 2018-04-22
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      相关资源
      最近更新 更多