問題描述
如何禁用墊下拉選項從一到二? (How to disable mat drop down option from one to two?)
TS 代碼:
import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
/**
* @title Basic use of `<table mat‑table>`
*/
@Component({
selector: 'table‑basic‑example',
styleUrls: ['table‑basic‑example.css'],
templateUrl: 'table‑basic‑example.html',
})
export class TableBasicExample {
timeSelection1='';
timeSelection2='';
resTimePeriodData= [
"1",
"2",
"3",
"4"
]
}
HTML 代碼:
<div class="row">
<div class="col‑md‑2 ">
<!‑‑ DROP DOWN FOR CURRENT TIME PERIOD ‑‑>
<mat‑form‑field>
<mat‑select placeholder="Current Time Period" multiple
name="select1" [(ngModel)]="timeSelection1" (ngModelChange)="onchange()" >
<mat‑option *ngFor="
let time1 of resTimePeriodData
" [value]="time1">{{ time1 }}</mat‑option>
</mat‑select>
</mat‑form‑field>
</div>
</div>
<div class="row">
<div class="col‑md‑2">
<mat‑form‑field >
<!‑‑ DROP DOWN FOR PREVIOUS TIME PERIOD ‑‑>
<mat‑select placeholder="Previous Time Period" multiple name="select2" [(ngModel)]="timeSelection2" >
<mat‑option *ngFor="
let time2 of resTimePeriodData
" [value]="time2">{{ time2 }}</mat‑option>
</mat‑select>
</mat‑form‑field>
</div>
</div>
如何禁用第一個選定元素以下拉兩個在下拉列表中選擇的元素。如果我在下拉菜單中選擇 3,然後在下拉菜單中選擇 2,如果我想從下拉菜單中選擇 2,我將被選中,並且兩個下拉菜單都具有相同的選項!
我的代碼試過 StackBlitz
參考解法
方法 1:
I would do something like this:
HTML:
<div class="row">
<div class="col‑md‑2 ">
<!‑‑ DROP DOWN FOR CURRENT TIME PERIOD ‑‑>
<mat‑form‑field>
<mat‑select [(value)]="selected" placeholder="Current Time Period" multiple name="select1" [(ngModel)]="timeSelection1">
<mat‑option *ngFor="let time1 of resTimePeriodData" [value]="time1">{{ time1 }}</mat‑option>
</mat‑select>
</mat‑form‑field>
</div>
</div>
<div class="row">
<div class="col‑md‑2">
<mat‑form‑field>
<!‑‑ DROP DOWN FOR PREVIOUS TIME PERIOD ‑‑>
<mat‑select placeholder="Previous Time Period" multiple name="select2" [(ngModel)]="timeSelection2">
<mat‑option *ngFor="let time2 of resTimePeriodData" [value]="time2" [disabled]="isDisable(time2)">{{ time2 }}</mat‑option>
</mat‑select>
</mat‑form‑field>
</div>
</div>
TS:
isDisable(obj) {
var index = this.selected.indexOf(obj);
if (index == ‑1) {
return false;
}
else {
return true;
}
}
You can also try to improve the existing code!
方法 2:
The value is being interpereted as a number. You can compare the time options in the disabled attribute using to string:
<mat‑option [disabled]="time2.toString() === timeSelection1.toString()" *ngFor="
let time2 of resTimePeriodData
" [value]="time2">{{ time2 }}</mat‑option>
I would recommend using numbers only though.
(by user10775755、Prashant Pimpale、De Wet van As)