如何修复角度下拉列表中的重复数据

时间:2019-05-11 10:14:44

标签: angular

我有两个下拉列表,其中有来自数据库的专家名称。例如,我在第一个下拉列表中选择了乔恩·史密斯,然后在第二个下拉列表中选择了乔恩·史密斯,因为它已经在第一个下拉列表中选择了。甚至有可能做到吗?

<td>
<select [(ngModel)]="survey.expertOne" class="form-control" name="expertOne + i">
<option *ngIf="survey.expertOne && survey.expertOne.name" value="{{survey.expertOne}}" disabled selected>{{survey.expertOne.name}}</option>
<option *ngFor="let expert of survey.experts" value="{{expert._id}}">{{expert.name}}</option></select>
</td>

<td>
<select [(ngModel)]="survey.expertTwo" class="form-control" name="expertTwo + i">
<option *ngIf="survey.expertTwo && survey.expertTwo.name" value="{{survey.expertTwo}}" disabled>{{survey.expertTwo.name}}</option>
<option *ngFor="let expert of survey.experts" value="{{expert._id}}">{{expert.name}}</option></select>
</td>

我希望在两个下拉列表中都无法选择相同的值。

2 个答案:

答案 0 :(得分:0)

我认为您必须使用此样式在所有选项中分配动态值:

<option *ngFor="let expert of survey.experts" [value]="expert._id">{{expert.name}}</option></select>

并尝试在两个选择标记中均不要使用“ export”关键字,例如,使用export1和expore2

答案 1 :(得分:0)

为了让您从“选择一个”到“选择两个”中删除一个选定的元素,最好的解决方案是创建两个包含相同专家列表的变量,selectOne遍历expertOne,selectTwo遍历ExpertTwo。然后使用事件侦听器,从一个数组或另一个数组中删除/添加选定/未选定的元素。

<td>
<select [(ngModel)]="survey.expertOne" (ngModelChange)="onExpertOneChange($event)" class="form-control" name="expertOne + i">
<option *ngIf="survey.expertOne && survey.expertOne.name" value="{{survey.expertOne}}" disabled selected>{{survey.expertOne.name}}</option>
<option *ngFor="let expert of experts1" value="{{expert._id}}">{{expert.name}}</option></select>
</td>

<td>
<select [(ngModel)]="survey.expertTwo" (ngModelChange)="onExpertTwoChange($event)" 
 class="form-control" name="expertTwo + i">
<option *ngIf="survey.expertTwo && survey.expertTwo.name" value="{{survey.expertTwo}}" disabled>{{survey.expertTwo.name}}</option>
<option *ngFor="let expert of experts2" value="{{expert._id}}">{{expert.name}}</option></select>
</td>

以及您的组件中:

//Arrays containing the same experts initially
experts1 :Expert[]
experts2 : Expert[]
//Experts used to readd the unselected element from one to another
expert1 :Expert
expert2:Expert
onExpertOneChange($event){
//This means that the expert is being unselected, so we need to push it back to list one
if(expert1 && expert1._id==$event)
this.experts2.push(expert1);
else
{
this.expert1 = this.experts1.find(x=> x._id==$event);
this.experts2=this.experts2.filter(x=>x._id!=$event);}
}}
onExpertTwoChange($event){
//This means that the expert is being unselected, so we need to push it back to list one
if(expert2 && expert2._id==$event)
this.experts1.push(expert2);
else
{
this.expert2 = this.experts2.find(x=>{return x._id==$event);
this.experts1=this.experts1.filter(x=>x._id!=$event);}
}}