如何限制angular2下拉列表中的重复值

how to restrict duplicate values from dropdown in angular2

这里我提到了当前的图像形式。

1) 它是一个多 select 下拉菜单。它应该限制重复的税名。 对于此图像中的示例,两次 CGST selected。

虽然 selecting 同名应该显示不在这里显示。 所以请帮我做这件事。

html

<div class="form-group">
  <label for="tax">Tax Name</label>
  <select class="form-control" id="tax_name" (change)=" dropdown(tax.value)" [(ngModel)]="model.tax" name="tax_name" #tax="ngModel">
    <option value="addNew">
      <i class="fa fa-plus" aria-hidden="true"></i>Add New Tax </option>
    <hr>
    <br/>
    <option *ngFor="let i of taxlist" [value]="i.tax_name">{{i.tax_name}} &nbsp; ( {{i.tax_percentage}}% )</option>
  </select>
</div>
<div>

  <label for="percentage">Tax Percentage</label>
  <input type="text" class="form-control" id="tax_percentage" placeholder="Percentage" pattern="[0-9]+" minlength="0" maxlength="3"
    [(ngModel)]="per" name="tax_percentage" #percentage="ngModel">
</div>
<button (click)="addContact(tax.value,percentage.value);" type="button" class="btn btn-success btn-sm text-right">
  <i class="fa fa-plus fa-lg"></i>
</button>

试试 Pipes 或者你可以使用新引入的 ES6 函数

var items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]
var uniqueItems = Array.from(new Set(items))

它将return独特的结果。

[1, 3, 4, 5, 2, 23]

好的。当您使用 *ngFor 循环值时,您必须删除列表中的所有重复条目。所以,好的方法是在 Angular 2+ 中创建一个过滤器,它被称为管道。它基本上是过滤器,将删除列表中的重复条目,因此用户将无法 select 多个相同的值,因为它们已被过滤且不存在于列表中。

@Pipe(name: 'unique') 
  export class FilterPipe implements PipeTransform
{

  transform(value: any, args?: any): any {

    // Remove the duplicate elements (this will remove duplicates
    let uniqueArray = value.filter(function (el, index, array) { 
      return array.indexOf (el) == index;
    });

  return uniqueArray;   } 

}

您将在 html 中使用此管道:

 <option *ngFor="let i of taxlist | unique" [value]="i.tax_name {{i.tax_name}} &nbsp; ( {{i.tax_percentage}}% )</option>

但请导入此 Pipe 并在您使用它的模块中注册它。

感谢 link 我之前在评论中提供过。