2017-09-23 100 views
2

我想創建一個帶複選框的下拉列表,以便用戶可以使用Material Design在Angular 2中選擇多個選項。angular2材質設計中的下拉列表複選框

默認情況下,我想要檢查所有複選框。我們如何做到這一點?

這是我的代碼的正常工作與複選框創建DDL:

<md-select multiple placeholder="Section List" [value]="section" options="true" (ngModelChange)='checkedSection();'> 
    <md-option *ngFor ="let section of selectedSectionList" > 
    {{section.sectionTitle}} 
</md-option> 

感謝,

回答

2

這裏是另外一個例子,可能看起來更有點像你的將是什麼樣子?

您需要在<md-option>標記中傳遞[value],而不是<md-select>標記。

您可以使用[(ngModel)]實現雙向數據綁定,其中包含一個變量,該變量最初包含所有選項的全部集合。這個變量將根據用戶輸入而改變。如果用戶取消選中一個框,則該值將被刪除。

所以我們需要另一個變量來迭代選項,以便它們在未選中時仍然顯示。

然後,您可以使用* ngFor遍歷包含要顯示的所有選項的另一個變量。

selectedSectionList = [{'sectionTitle': 'Title 1', 'sectionOther': 'awesome stuff'}, 
    {'sectionTitle': 'Title 2', 'sectionOther': 'awesome stuff'}, 
    {'sectionTitle': 'Title 3', 'sectionOther': 'awesome stuff'}, 
    {'sectionTitle': 'Title 4', 'sectionOther': 'awesome stuff'}, 
    ]; 

    sectionsSelected = this.selectedSectionList; 

和你的HTML看起來像這樣

<md-select multiple placeholder="Section List" [(ngModel)]="sectionsSelected"> 
    <md-option *ngFor ="let section of selectedSectionList" [value]="section"> 
    {{section.sectionTitle}} 
    </md-option> 
</md-select> 
2

您需要的[值]在<md-option>標籤傳遞,不<md-select>標記。

例如,這個工程:

sectionsSelected = ['A', 'B', 'C', 'D']; 
AllSections = ['A', 'B', 'C', 'D']; 

然後在你的HTML

<md-select multiple placeholder="Section List" 
[(ngModel)]="sectionsSelected"> 
    <md-option *ngFor ="let section of AllSections" [value]="section"> 
    {{section}} 
    </md-option> 
</md-select>