2016-08-23 108 views
0

我想写一个自定义指令,如果用户在下拉菜单中选择“全部”选项,它会自动选择所有选项我已经能够获得我的自定义指令选择所有选项但这不会更新耗用组件上的模型。Angular2自定义指令双向绑定

自定义指令

@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和使用香蕉在一个盒子里的语法,试图更新模型,我是不是成功的接着就,随即。

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

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

在此先感谢

回答

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

+0

谢谢史蒂文工作的一种享受! – Macilquham