多个选项具有相同的选项

时间:2018-05-24 17:39:59

标签: javascript angular angular2-forms

Mockup

我需要使用相同的选项集创建多个选择,如上面的模型所示。需要从所有其他选项中删除所选选项,如图所示。我如何在Angular中实现这一目标?这是我写的内容的片段。

(change)="fetchProductTypeForCategory($event)"

我尝试使用管道过滤掉所选的选项,但它无法识别更改。我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以在* ngFor表达式中对数组上调用的组件创建方法。此方法可以筛选出在先前选择中已经对某个索引进行的选择。

组件方法

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

<强>模板

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

答案 1 :(得分:0)

我建议为你的目的写一个过滤管。

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));
  }
}

然后你可以像

一样使用它
<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>

如果您想使用动态数量的选择,请尝试使用Reactive Forms,因为它们提供了非常方便的FormArray。

编辑完整性:在相应的模块中,您必须声明管道

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