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

Har*_*ath 3 angular2-forms angular2-directives angular2-template angular

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

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

选择相同的名称时,它不应显示在此处。所以请帮助我做到这一点。

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>
Run Code Online (Sandbox Code Playgroud)

小智 6

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

@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;   } 
Run Code Online (Sandbox Code Playgroud)

}

你将在 html 中使用这个管道:

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

但是请导入这个 Pipe 并在你正在使用它的模块中注册它。

感谢我之前在评论中提供的链接。