2 回答
TA贡献1835条经验 获得超7个赞
一种方法是根据您的要求构建模型。您目前有 2 个下拉菜单,但只有一个列表同时驱动它们。
相反,我会为每个选择创建一个数组,并将所选值绑定到每个下拉列表的属性。然后,当值更改时重建数组变得相当简单。
<mat-form-field>
<mat-select [(ngModel)]="selected1" (selectionChange)="change1()" placeholder="Custom placeholder">
<mat-option *ngFor="let item of filtered1" [value]="item.id">
{{item.name}}
</mat-option>
</mat-select>
</mat-form-field>
<br>
<mat-form-field>
<mat-select [(ngModel)]="selected2" (selectionChange)="change2()" placeholder="Using array of objects">
<mat-option *ngFor="let item of filtered2" [value]="item.id">
{{item.name}}
</mat-option>
</mat-select>
</mat-form-field>
filtered1: {}[];
filtered2: {}[];
selected1: number;
selected2: number;
private options = [
{
id: 0,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
},
{
id: 3,
name: 'd'
}
];
ngOnInit() {
this.selected1 = this.options[0].id;
this.selected2 = this.options[1].id;
this.change1();
this.change2();
}
change1() {
this.filtered2 = this.options.filter(x => x.id !== this.selected1);
}
change2() {
this.filtered1 = this.options.filter(x => x.id !== this.selected2);
}
演示:https ://stackblitz.com/edit/mat-select-filter-2usqw5
TA贡献1820条经验 获得超2个赞
你可以试试以下
零件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
dropdownOne: string;
dropdownTwo: string;
public variables2 = [
{
id: 0,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
},
{
id: 3,
name: 'd'
}
];
public filteredList5 = this.variables2.slice();
change(e){
}
}
模板
<mat-form-field>
<mat-select [(ngModel)]="dropdownOne" (selectionChange)="change($event)" placeholder="Custom placeholder">
<ng-container *ngFor="let item of filteredList5">
<ng-container *ngIf="item != dropdownTwo">
<mat-option [value]="item">
{{item.name}}
</mat-option>
</ng-container>
</ng-container>
</mat-select>
</mat-form-field>
<br>
<mat-form-field>
<mat-select [(ngModel)]="dropdownTwo" (selectionChange)="change($event)" placeholder="Using array of objects">
<ng-container *ngFor="let item of filteredList5">
<ng-container *ngIf="item != dropdownOne">
<mat-option [value]="item">
{{item.name}}
</mat-option>
</ng-container>
</ng-container>
</mat-select>
</mat-form-field>
下拉列表中的值绑定到变量dropdownOne和dropdownTwo. 在选项循环中,在显示选项之前检查选项的值是否不等于另一个下拉列表的选定值。由于我们在显示之前检查项目,因此可以从更改事件处理程序中删除过滤器。
添加回答
举报