angular2材质设计中的下拉列表复选框
问题描述:
我想创建一个带复选框的下拉列表,以便用户可以使用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>
感谢,
答
这里是另外一个例子,可能看起来更有点像你的将是什么样子?
您需要在<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>
答
您需要的[值]在<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>