我有两个选择垫的下拉菜单。 在第一个下拉菜单中,我具有a,b,c,d之类的值 在第二个下拉列表中,我具有相同的值,例如a,b,c,d
要求
当我选择第一个下拉列表时,从第一个下拉列表中选择的值不应出现在“第二个下拉列表”中,反之亦然。 例如,我在第一个下拉列表中选择了“ b”值,而不是在第二个下拉列表中选择了“ b”,而仅出现a,c,d。
https://stackblitz.com/edit/mat-select-filter-nayx2k?embed=1&file=src/app/app.component.html
从上面的stackblitz中,我可以过滤值,但其他下拉值的默认值已删除。
答案 0 :(得分:0)
您可以尝试以下
组件
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
。并且在选项循环中,在显示选项之前,检查选项的值是否不等于另一个下拉菜单的选定值。由于我们在显示之前检查了该项目,因此可以从更改事件处理程序中删除该过滤器。
我已经修改了您的Stackblitz
答案 1 :(得分:0)
执行此操作的一种方法是根据您的要求构建模型。您目前有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);
}
答案 2 :(得分:0)
请检查此演示您在同一阵列上操作,这就是为什么它不起作用