【问题标题】:Remove selected option from drop down in Angular从 Angular 的下拉列表中删除选定的选项
【发布时间】:2020-11-13 09:06:53
【问题描述】:

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

以下代码用于下拉选择:

<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 将从下拉列表中删除。如何解决此问题并仅删除下一个选择下拉菜单的选项?

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

您可以尝试创建两个环境对象并使用 formControl 中的 valueChanges 监听选择。获得选定的 environmentid 并过滤没有此 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

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 2020-01-10
    • 1970-01-01
    • 2021-04-16
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多