0

我試圖在mat-select中單擊一個按鈕來實現多個選項,選項應該取消選中,並且應該從檢查列表中刪除。動態取消選中md-select angular 4.x中的多個選擇選項

去除所選的選項我寫我的代碼如下:

墊選擇選項:

<mat-form-field class="full-width"> 
      <mat-select class="multiple-location-list-search-wrapper full-width" #mulLoc required placeholder="Locations" multiple> 
      <mat-option *ngFor="let l of locationsBasedOnPropertyType; let i = index" class="multiple-field-box" [hidden]="tempLocations[i]" 
       [value]="l"> 
       {{ l.value }} 
      </mat-option> 
      </mat-select> 
     </mat-form-field> 

刪除按鈕:

<span (click)="deleteLocation(i, mulLoc);">Delete Location</span> 
      <p> 
      <strong>{{mulLoc.value[i].value}}</strong> 
      </p> 

刪除功能:

deleteLocation(index, multipleLocation){ 
    multipleLocation.selected[index]._selected = false; 
    multipleLocation.selected[index]._active = false; 
    multipleLocation.selected.splice(index,1); 
    multipleLocation.value.splice(index,1); 
    } 

通過執行上述操作,我可以從selected & value數組中刪除選項,但它並未反映在Material UI中。位置選項沒有被取消選中。

是否有任何黑客或內部方法做同樣的事情?

在此先感謝!

回答

0

@威爾豪爾,感謝您的幫助人。

但我有我的解決方案如下圖所示:

我做了一些研究
'..app-folder../node_modules/@angular/material/select/typings/select.d.ts'
我發現
writeValue(value: any): void;

我在視圖中所做的更改:

<mat-select class="full-width" #mulLoc required placeholder="Locations" multiple [(ngModel)]="resLoc" name="resLoc"> 
    <mat-option *ngFor="let l of locations; let i = index [hidden]="tempLocations[i]" [value]="l"> 
{{ l.value }} 
</mat-option> 
</mat-select> 

對象:

locations = [ 
{id : 'IND',value : 'india'}, 
{id : 'INS',value : 'indonesia'}, 
{id : 'THL',value : 'thailand'} 
] 
resLoc = [locations[0], locations[2]] 

組件:這是我要求刪除(取消選擇)位置

deleteLocation(i,mulLoc) { 
    this.resLoc.splice(i,1); // my ngModel 
    mulLoc.writeValue(this.resLoc); // reference variable of mat-select 
    } 

希望它能幫助的功能!快樂的編碼!

0

我怕我不完全瞭解如何以及何時選項被刪除,但在這裏,似乎滿足您的需要

toppings = new FormControl(); 

toppingList = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato']; 

remove(topping: string) { 
    // Remove from form control value 
    const selectedIndex = this.toppings.value && this.toppings.value.indexOf(topping) 
    if (selectedIndex > -1) { 
    const newToppingsValue = this.toppings.value.slice(); 
    newToppingsValue.splice(selectedIndex, 1); 
    this.toppings.setValue(newToppingsValue); 
    } 

    // Remove from topping list 
    const listIndex = this.toppingList.indexOf(topping); 
    if (listIndex > -1) { 
    this.toppingList.splice(listIndex, 1); 
    } 

} 

WORKING EXAMPLE


編輯爲例:這裏的一個example選項沒有被刪除,只是取消選擇。

+0

我不想刪除選項,我只是想取消選中它。 –

+0

哼好吧,[這個例子]怎麼樣(https://stackblitz.com/edit/material2-beta12-ygj9vj?file=app%2Fapp.component.ts) –

相關問題