2016-08-25 26 views
0

我創建了一個簡單的工具,使用select來添加和刪除列表中的英雄。爲Angular 2重構JavaScript腳本

當選擇英雄時,它被添加到數組myheroes並顯示爲列表項目。所選英雄在select也被禁用。

當英雄從列表中刪除時,它將在select中啓用,因此可以再次選擇英雄。

這可以按預期工作,但是我覺得必須有更好更優雅的方法來使用Angular 2的功能。一個屬性指令,用於偵聽對myheroes的更改。

歡迎任何建議/指導。

Plnkr

@Component({ 
    selector: 'my-app', 
    template: ` 
    <p>My heroes:</p> 
    <ul> 
    <li *ngFor="let myhero of myheroes"> 
     {{ myhero }} 
     <a href="#" (click)="deleteItem(myhero)">x</a> 
    </li> 
    </ul> 
    <select id="hero" #hero (change)=addItem(hero)> 
    <option>Select a hero</option> 
    <option *ngFor="let hero of heroes">{{ hero }}</option> 
    </select> 
` 
}) 
export class AppComponent { 
    heroes = ['Windstorm','Bombasto','Magneta','Tornado']; 
    myheroes= []; 

    deleteItem(item: string) { 
    const index = this.myheroes.indexOf(item); 
    this.myheroes.splice(index, 1); 
    //TODO enable item in select options 
    const output = document.getElementById('hero').options; 

    for(const i=0;i<output.length;i++) { 
     if(output[i].value == item){ 
     output[i].disabled = false; 
     } 
    } 
    } 

    addItem(item: HTMLSelectElement) { 
    if(item.value != 'Select a hero') { 
     this.myheroes.push(item.value); 
     item.options[item.selectedIndex].disabled = true; 
    } 
    } 
} 
+0

其工作很好你期望除了這個使用angular2? –

+0

感覺像啓用/禁用選擇選項的行爲屬於它自己的組件 – user1405195

回答

1

HTML選項有一個可以綁定到[disabled]="<condition>"禁用的屬性,所以這將是處理的選擇選項啓用/禁用,而在使用的文件選擇器的首選方式。

如果您要改變使用這個,那麼就沒有必要分開處理這個功能了。

此外,關於您的代碼示例的補充一點 - 您可能希望重置更改事件處理中select內部的值,因爲如果選擇某個項目並立即將其從列表中刪除,那麼如果沒有先選擇另一個項目,則無法將該項目添加到列表中,因爲只有在綁定到選擇的模型發生更改時纔會觸發更改事件。