I would like to create a dropdown list with checkboxes so the users can select multiple options in Angular 2 using Material Design.
By default, I would like to have all the checkboxes checked. How do we do this?
This is my code which works fine for creating the DDL with checkboxes:
<md-select multiple placeholder="Section List" [value]="section" options="true" (ngModelChange)='checkedSection();'>
<md-option *ngFor ="let section of selectedSectionList" >
{{section.sectionTitle}}
</md-option>
Thanks,
You need the [value] to be passed in the <md-option>
tag, not the <md-select>
tag.
For example, this works:
sectionsSelected = ['A', 'B', 'C', 'D'];
AllSections = ['A', 'B', 'C', 'D'];
Then in your html
<md-select multiple placeholder="Section List"
[(ngModel)]="sectionsSelected">
<md-option *ngFor ="let section of AllSections" [value]="section">
{{section}}
</md-option>
</md-select>
Here's another example that probably looks a little more like what yours will look like...
You need the [value]
to be passed in the <md-option>
tag, not the <md-select>
tag.
You can use [(ngModel)]
to implement two-way data binding with a variable that initially holds the full set of all options. This variable will change based on user input. If a user unchecks a box, that value will be dropped.
So we need another variable to iterate over for the options, so that they still show up when they are unchecked.
Then you can use *ngFor to iterate over another variable containing all options to display.
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;
and your HTML would look like this
<md-select multiple placeholder="Section List" [(ngModel)]="sectionsSelected">
<md-option *ngFor ="let section of selectedSectionList" [value]="section">
{{section.sectionTitle}}
</md-option>
</md-select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.