简体   繁体   English

具有相同选项的多项选择

[英]Multiple selects with the same options

小样

I need to create multiple select with the same set of options, as illustrated in the mockup above. 我需要使用相同的选项集创建多个选择,如上面的模型所示。 Selected options need to be removed from all the other selects, as shown in the picture. 如图所示,需要从所有其他选择中删除选定的选项。 How do I achieve this in Angular? 如何在Angular中实现这一目标? Here is a snippet of what I have written. 这是我所写内容的摘录。

<div class="card-deck mb-3 text-center">
  <div *ngFor="let index of [0, 1, 2, 3]" class="card mb-4">
    <div class="card-header">
      Destination {{ index + 1 }}
    </div>
    <div class="card-body">
      <div class="input-group mb-3">
        <select class="form-control" [(ngModel)]="selectedPlanets[index]">
          <option *ngFor="let planet of planets" [value]="planet.name">
            {{planet.name}}
          </option>
        </select>
      </div>
    </div>
  </div>
</div>

I have tried using a pipe to filter out the selected options, but it does not recognize changes. 我尝试使用管道过滤掉选定的选项,但它无法识别更改。 How do I achieve this? 我该如何实现?

You can make a method on your component that is called on the array in the *ngFor expression. 您可以在组件上创建一个方法,该方法在* ngFor表达式中的数组上调用。 This method can filter out selections that have already been made in previous choices to a certain index. 此方法可以将先前选择中已经选择的选择过滤到某个索引。

Component method 组成法

filterChoices(choices: [], selections: [], maxIndex) {
  const inBoundsSelections = selections.filter((x, i) => i <= maxIndex);
  return choices.filter(x => inBoundsSelections.indexOf(x) === -1);
}

Template 模板

<option 
   *ngFor="let planet of filterChoices(planets, selectedPlanets, index - 1)"
   [value]="planet.name">
  {{planet.name}}
</option>

I suggest to write a filtering pipe for your purpose. 我建议您编写一个过滤管道。

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'remove'})
export class RemovePipe implements PipeTransform {
  transform(options: string[], toRemove: string[]): string[] {
    return options.filter(option => !toRemove.includes(option));
  }
}

Then you can use it like 然后你可以像

<select #name1>
  <option [value]="planet.name" *ngFor="let planet of planets"></option>
</select>
<select #name2>
  <option [value]="planet.name" *ngFor="let planet of planets | remove:[name1.value]"></option>
</select>
<select #name3>
  <option [value]="planet.name" *ngFor="let planet of planets | remove:[name1.value, name2.value]"></option>
</select>

If you want to use a dynamic number of selects, try using Reactive Forms as they provide the very handy FormArray. 如果要使用动态数量的选择,请尝试使用反应式表单,因为它们提供了非常方便的FormArray。

Edit for completeness: In the corresponding module you have to declare the pipe 编辑完整性:在相应的模块中,您必须声明管道

import { RemovePipe } from 'pathto/remove.pipe'
@NgModule({
  declarations: [ RemovePipe ]
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM