从Angular下拉菜单中删除所选选项

时间:2020-07-23 15:20:49

标签: javascript angular typescript

我有一个按钮,单击后会添加更多选择下拉菜单。因此,我想删除这些选择框中已经选择的选项,以防止重复。

以下代码用于选择下拉列表:

<select class="select form-control"
   formControlName="environment_id" (change)="onEnvChange($event.target.value)">
   <option selected="selected" disabled value="">Select Environment
   </option>
   <ng-container  *ngFor="let environment of environments">
      <option *ngIf="!selectedEnvironments.includes(environment.environment_id)"
      [value]="environment.environment_id">
      {{environment.environment_id}}</option>
   </ng-container>
</select>

,在该组件中,我为change

具有以下功能
 public onEnvChange(selectedEnvironment)
 {
     this.selectedEnvironments.push(selectedEnvironment);
 }

现在,当我选择一个选项时,该选项本身将从下拉列表中删除。例如,如果我有诸如option1,option2,option3之类的选项,则当我选择option1时,option1将从下拉列表中删除。如何解决此问题并仅删除下一个选择下拉菜单的选项?

1 个答案:

答案 0 :(得分:0)

您可以尝试创建两个环境对象,并使用formControl中的valueChanges侦听选择。获得选定的环境ID并过滤没有该ID的其他对象

示例

  ngOnInit(){
    this.createForm();
    this.getEnvironments();
    this.environmentChanges()
  }

  createForm(){
      this.form = this.fb.group({
           'environment_id_1': [''],
           'environment_id_2' : ['']
})}

  getEnvironments(){
      const environments = [
      {  'environment_id': 1, 'environment': 'A'  },
      {  'environment_id': 2, 'environment': 'B'  },
      {  'environment_id': 3, 'environment': 'C'  },
      {  'environment_id': 4, 'environment': 'D'  }];
      this.environments1 = environments;
      this.environments2 = environments;}

  environmentChanges(){
     this.form.controls['environment_id_1'].valueChanges
             .subscribe((environment_id)=>{
             this.environments2 = this.environments1.filter((env)=> env.environment_id != environment_id)
})}

<form [formGroup]="form">
<div class="row">
    <select class="select form-control"   formControlName="environment_id_1">   
        <option value="">Select Environment 1 </option> 
        <option *ngFor="let environment of environments1"  [value]="environment.environment_id"> {{environment.environment}} </option> 
    </select>
</div>
<div class="row" style="padding-top: 10px;">
    <select class="select form-control"   formControlName="environment_id_2">   
        <option value="">Select Environment 2 </option> 
        <option *ngFor="let environment of environments2"  [value]="environment.environment_id"> {{environment.environment}} </option> 
    </select>
</div>

enter image description here