我使用角4并使用最新的材料。当我使用带有多个选择选项的md-select但我希望有一个opiton“全选”将选择所有选项存在。我该怎么办?
<md-select multiple>
<md-option> Select All </md-option>
<md-option> Option 1 </md-option>
<md-option> Option 2 </md-option>
<md-option> Option 3 </md-option>
</md-select>
答案 0 :(得分:0)
我在mat-select内添加了复选框,并且将设计更改为看起来像mat-select的一部分
TS: @ViewChild('select')选择:MatSelect;
onAllChanged(checked: any) {
if (checked) {
this.select.value = //add all your choices
} else {
this.select.value = [];
}
}
selectionchanged() {
if (this.selectedValues.length === yourlist.length) {
this.allchecked = true;
} else {
this.allchecked = false;
}
}
HTML:
<mat-form-field>
<mat-select #select="matSelect"
(selectionChange)="selectionchanged()" [(ngModel)]="selectedValues" multiple>
<mat-checkbox [(ngModel)]="allchecked"
(change)="onAllChanged($event.checked)" style="padding-left:15px;">
All
</mat-checkbox>
<mat-option>option1<mat-option>
<mat-option>option2<mat-option>
<mat-option>option3<mat-option>
</mat-select>
</mat-form-field>
答案 1 :(得分:-1)
我想出了一个关于select的值变化的回调,然后检查第一个选择的选项是否没有值,然后重置formControl(这个解决方案是用于反应形式。它应该很容易适应模型形式)
<强> HTML:强>
<mat-select formControlName="myControl" multiple (ngModelChange)="resetSelect($event, 'myControl')">
<mat-option>Select All</mat-option>
<mat-option [value]="1">Option 1</mat-option>
<mat-option [value]="2">Option 2</mat-option>
<mat-option [value]="3">Option 3</mat-option>
</mat-select>
<强> TS:强>
/**
* click handler that resets a multiple select
* @param {Array} $event current value of the field
* @param {string} field name of the formControl in the formGroup
*/
protected resetSelect($event: string[], field: string) {
// when resetting the value, this method gets called again, so stop recursion if we have no values
if ($event.length === 0) {
return;
}
// first option (with no value) has been clicked
if ($event[0] === undefined) {
// reset the formControl value
this.myFormGroup.get(field).setValue([]);
}
}
这样可行,但感觉有点脏。 setValue()
当然会触发ngModelChange
,因此我们会进行递归,我只是停留$event.length === 0
。另外,检查值为undefined
的第一个选项似乎有点...... meeeeh ......
如果有人能提供更优雅的解决方案,我将不胜感激!