我已经结合了 mat-chips 自动完成和输入(因为两者都出现在文档的示例部分),但是它产生了一个问题,当我输入部分自动完成选项来过滤选项,然后单击它时,它会添加输入值加上点击的项目到筹码列表。这对它来说可能是一件非常合乎逻辑的事情,因为我看不出有任何理由为什么它应该在单击项目时忽略模糊事件,是否有内置的方法/黑客来解决这个问题?这是我的代码:
<mat-form-field class="chip-list">
<mat-chip-list #chipList aria-label="Op selection" class="mat-chip-list-stacked">
<mat-basic-chip *ngFor="let sop of selectedOps" [selectable]="selectable"
[removable]="removable" (removed)="remove(sop)">
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
{{sop.val}}
</mat-basic-chip>
</mat-chip-list>
<div style="position: relative;">
<input matInput [formControl]="chipControl" aria-label="subcats" #SelectInput
[matAutocomplete]="auto" [matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
(matChipInputTokenEnd)="add($event)" [matChipInputAddOnBlur]="addOnBlur">
<mat-icon class="icon" (click)="SelectInput.focus()">keyboard_arrow_down</mat-icon>
</div>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let op of filteredOps | async" [value]="op">
<div (click)="optionClicked($event, op)">
<mat-checkbox [checked]="op.selected" (change)="toggleSelection(op)"
(click)="$event.stopPropagation(); ">
{{ op.val }}
</mat-checkbox>
</div>
</mat-option>
</mat-autocomplete>
</mat-form-field>
我做错了什么吗?还是一开始就不应该一起工作?感谢您的任何反馈!
最佳答案
这是@ https://github.com/angular/components/issues/19279#issuecomment-627263513 发布的解决方案
从那里报价:
我们可以模拟 matChipInputAddOnBlur 自身。
我在输入中添加了 (blur)=addOnBlur($event) 并禁用了 matChipInputAddOnBlur。
点击 mat-input 应该被忽略。
我的实现:
addOnBlur(event: FocusEvent) {
const target: HTMLElement = event.relatedTarget as HTMLElement;
if (!target || target.tagName !== 'MAT-OPTION') {
const matChipEvent: MatChipInputEvent = {input: this.fruitInput.nativeElement, value : this.fruitInput.nativeElement.value};
this.add(matChipEvent);
}
}
示例 https://stackblitz.com/edit/angular-rd38q1-jxbjjb?file=src%2Fapp%2Fchips-autocomplete-example.ts
关于带有 mat-autocomplete 和输入组合的 Angular mat-chips,从列表中选择时添加一个额外的芯片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62644795/