Angular 如何停止在自动完成组件中添加重复芯片?

Angular 如何停止在自动完成组件中添加重复芯片?,angular,angular-material,Angular,Angular Material,如何停止使用角材质碎片在列表中添加重复值?例如,我只想在水果列表中添加一个苹果,当我添加柠檬时,我只想添加一个。现在我可以添加多次。当我关闭芯片时,我希望能够再次添加它。我将感谢任何帮助。谢谢 从“@angular/cdk/keycodes”导入{逗号,输入}; 从“@angular/core”导入{Component,ElementRef,ViewChild}; 从'@angular/forms'导入{FormControl}; 从“@angular/material”导入{MatAutoco

如何停止使用角材质碎片在列表中添加重复值?例如,我只想在水果列表中添加一个苹果,当我添加柠檬时,我只想添加一个。现在我可以添加多次。当我关闭芯片时,我希望能够再次添加它。我将感谢任何帮助。谢谢

从“@angular/cdk/keycodes”导入{逗号,输入};
从“@angular/core”导入{Component,ElementRef,ViewChild};
从'@angular/forms'导入{FormControl};
从“@angular/material”导入{MatAutocompleteSelectedEvent,MatchiPiInputEvent};
从“rxjs”导入{Observable};
从“rxjs/operators”导入{map,startWith};
/**
*@title芯片自动完成
*/
@组成部分({
选择器:“芯片自动完成示例”,
templateUrl:'chips autocomplete example.html',
样式URL:['chips-autocomplete-example.css']
})
导出类芯片SautoComplete示例{
可见:布尔值=真;
可选:布尔值=真;
可移动:布尔值=真;
addOnBlur:boolean=false;
separatoreyscodes=[输入,逗号];
fruitCtrl=新表单控件();
过滤果:可见;
水果=[
“柠檬”,
];
所有水果=[
“苹果”,
“柠檬”,
“石灰”,
“橙色”,
“草莓”
];
@ViewChild('fruitInput')fruitInput:ElementRef;
构造函数(){
this.filteredFruits=this.fruitCtrl.valueChanges.pipe(
startWith(空),
map((fruit:string | null)=>fruit?this.filter(fruit):this.allFruits.slice());
}
添加(事件:MatChipInputEvent):无效{
常量输入=event.input;
常量值=event.value;
//加上我们的水果
如果((值| |“”).trim()){
this.fruits.push(value.trim());
}
//重置输入值
如果(输入){
input.value='';
}
this.fruitCtrl.setValue(null);
}
移除(水果:任何):无效{
const index=this.fruits.indexOf(fruit);
如果(索引>=0){
这个。水果。剪接(索引,1);
}
}
过滤器(名称:字符串){
返回此.allFruits.filter(fruit=>
fruit.toLowerCase().indexOf(name.toLowerCase())==0);
}
已选择(事件:MatAutocompleteSelectedEvent):无效{
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value='';
this.fruitCtrl.setValue(null);
}
}
/**版权所有2018谷歌公司。保留所有权利。
此源代码的使用受MIT风格的许可证管理,该许可证
可以在以下位置的许可证文件中找到:http://angular.io/license */

{{水果}
取消
{{水果}

您可以检查该项是否已存在于数组中,然后添加

试着这样做:

// Add our fruit
if ((value || '').trim()) {
  if(!this.fruits.includes(value.trim())) {
    this.fruits.push(value.trim());
  }
}
<mat-option *ngIf="!fruits.includes(fruit)" [value]="fruit">
  {{fruit}}
</mat-option>


如果已添加芯片,则可以检查所选事件。替换此项:

  selected(event: MatAutocompleteSelectedEvent): void {
    this.fruits.push(event.option.viewValue);
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }
为此:

  selected(event: MatAutocompleteSelectedEvent): void {
    if (!this.fruits.includes(event.option.viewValue)) {
      this.fruits.push(event.option.viewValue);
    }
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }

要将其从列表中删除,请在已添加元素时将其从选项中删除,如下所示:

// Add our fruit
if ((value || '').trim()) {
  if(!this.fruits.includes(value.trim())) {
    this.fruits.push(value.trim());
  }
}
<mat-option *ngIf="!fruits.includes(fruit)" [value]="fruit">
  {{fruit}}
</mat-option>

{{水果}

你能在stackbiltz中共享你的代码吗?这对我来说很有效,只会防止再次添加,但仍然显示在列表上。你可以更改过滤功能以排除芯片中存在的结果。选择芯片后,这不起作用。autocomplete将显示相同的选项。但是,单击后将不再添加选定的芯片@卢西安·波帕