下拉菜单- Angular2在SELECT中选择的选项从所有其他SELECT标签选项中移除



我有几个下拉菜单,都有相同的初始选项。(它们可以在开始时用一个值初始化)。我在一个下拉菜单中选择一个选项时寻找解决方案-它将不再显示为其他下拉菜单中的选项。我在AngularJS中看到了这个解决方案,但在Angular 2 RC 4中没有成功:https://stackoverflow.com/a/28918935

另外,我发现在Angular.io中不建议使用管道进行过滤:

Angular团队和许多经验丰富的Angular开发人员建议将过滤和排序逻辑移到组件中本身。

我有一个解决这个问题的办法:

在html

:

<select [ngModel]='currValue'
        (change)="update($event.target.value, i, $event.target.options.selectedIndex)"
         name="{{i}}"
         #select>
                <option *ngFor="let currItem of items | distinctValue: selectedList: select.value: i: currValue; let j=index"
                        value="{{currItem}}">{{currItem}}</option>
</select>
在ts

:

selectedList: any = [];

当更改select的选定值时-将项目推入selectedList并从selectedList中删除该元素的先前选定值,以便可以再次选择。

在DistinctValue.pipe.ts

:

transform(itemsList: any, filtersList: any, excludeItem: any, row: any, currItem: any) {
  return itemsList.filter(function(option:any) {
      let keepItem: boolean = true;
      let currFilter: number = 0;
      // Check if the option should be filtered
      while ((keepItem) && (currFilter < filtersList.length)) {
        // If option exists in filters list and not this item
        if ( (option.fieldname != currItem.fieldname)
              (option.fieldname != excludeItem.fieldname) &&
              (option.fieldname == filtersList[currFilter].fieldname) ) {
            keepItem = false;
        }
        currFilter++;
      }
      return keepItem;
    });

}

您可以编写一个自定义过滤器管道。

html:

options | optionFilter:optionToRemove

js:

@Pipe({
    name: 'optionFilter'
})
class OptionFilterPipe implements PipeTransform {
    public transform(options, optionToRemove) {
        return options.filter(function(option) {return option.id !== optionToRemove.id)};
    }
}

最新更新