gpt4 book ai didi

Angular Autocomplete - 选择元素时从列表中删除元素

转载 作者:行者123 更新时间:2023-12-04 14:37:27 24 4
gpt4 key购买 nike

我正在尝试开发一个自动完成。我的问题是我无法从列表中删除被选中的元素。

图片说明了我的问题

Image

我选择了一个名称,然后选择了相同的连续名称 n 下拉列表 :( 当它被选中时它应该“消失”

我的代码--Stackblitz

Stackbiltz

组件

constructor(private userService: UserService) {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}

ngOnInit() {
this.userService.getUsers().subscribe(
(val: any[]) =>{
this.allFruits = val.map(user => user.username);
this.fruitCtrl.setValue(null);
}
)
}

remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);

if (index >= 0) {
this.fruits.splice(index, 1);
}
}

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

private _filter(value: string): string[] {
const filterValue = value.toLowerCase();

return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
}

HTML
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList>
<mat-chip
*ngFor="let fruit of fruits"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(fruit)">
{{fruit}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input
placeholder="New fruit..."
#fruitInput
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
{{fruit}}
</mat-option>
</mat-autocomplete>
</mat-form-field>

最佳答案

像这样用 ngIf 排除选定的水果:

<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<ng-container *ngFor="let fruit of filteredFruits | async">
<mat-option *ngIf="!fruits.includes(fruit)" [value]="fruit">
{{fruit}}
</mat-option>
</ng-container>
</mat-autocomplete>

关于Angular Autocomplete - 选择元素时从列表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com