2016-08-23 107 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