【问题标题】:how to restrict duplicate values from dropdown in angular2如何限制angular2下拉列表中的重复值
【发布时间】:2018-10-23 03:48:32
【问题描述】:

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

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>

【问题讨论】:

标签: angular angular2-template angular2-forms angular2-directives


【解决方案1】:

好的。当您使用 *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;   } 

}

您将在 html 中使用此管道:

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

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

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

【讨论】:

    【解决方案2】:

    试试 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))
    

    它将返回唯一的结果。

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

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多