html - Material angular 自动完成:在选择一个选项后如何让 mat-option 保留在屏幕上?
我正在使用 Material 自动完成 Angular。 在我选择了 mat-option 列表中的一个选项后,我的 mat-options 会隐藏。我需要在选择后保留这些选项。GIF 显示了问题:
我的 HTML
<div class="col-xl-6 margemColunas">
<label>Anunciaremos nas contas *</label>
<input class="form-control inputContasB2W"
#inputContasB2W
[formControl]="contasB2WControl"
[matAutocomplete]="auto"
(matChipInputTokenEnd)="add($event)">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event, i)">
<mat-option *ngFor="let contaB2W of contasFiltradas | async" [value]="contaB2W">
{{contaB2W}}
</mat-option>
</mat-autocomplete>
</div>
<div class="col-xl-6 alinhaChips">
<mat-chip-list>
<mat-chip
*ngFor="let contaB2W of produto.contasAnunciarB2W; let j = index"
[selectable]="selected"
[removable]="removable"
(removed)="removeTag(i, j)">
{{contaB2W}}
<mat-icon matChipRemove><i class="fa fa-close"></i></mat-icon>
</mat-chip>
</mat-chip-list>
</div>
我的ts:
constructor(){
this.contasFiltradas = this.contasB2WControl.valueChanges.pipe(
startWith(null),
map((nomeConta: string | null) => nomeConta ? this._filter(nomeConta) : this.contasB2W.slice()));
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.contasB2W.filter(conta => conta.toLowerCase().indexOf(filterValue) === 0);
}
selected(event: MatAutocompleteSelectedEvent, index: number): void {
this.produtosConfirmadosAnuncio[index].contasAnunciarB2W.push(event.option.viewValue);
this.inputContasB2W.nativeElement.value = '';
}
}
答案#1
我使用了变通方法先对输入框 blur(),然后再 focus()。
在 ts 中:
@ViewChild('inputContasB2W') autocompleteInput: ElementRef;
selected(event: MatAutocompleteSelectedEvent) {
[..do your stuff...]
this.autocompleteInput.nativeElement.blur();
setTimeout(() => {
this.autocompleteInput.nativeElement.focus();
}, 100
);
}
如果你想保留输入文本,你必须将其保存到 _filter() 中,并在 blur() 之前再次设置值,比如 this.contasB2WControl.setValue(this.lastFilterValue);
答案#2
解决方案相对简单。你必须阻止点击的传播,但当点击到达 mat-option 时已经太晚了。然后使用 span 标签添加一个不可见的预层:
...
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let contaB2W of contasFiltradas | async" [value]="contaB2W"
style="position: relative;">
<span style="position: absolute; top: 0; left: 0; bottom: 0; right: 0;"
(click)="doWhateverWith(contaB2W); $event.stopPropagation()">
{{contaB2W}}
</span>
</mat-option>
</mat-autocomplete>
...
- 添加了一个带有样式
position: absolute的span,其top,left,bottom,right设置为0。 - 在
mat-option添加了position: relative样式,以便 span 能正确展开。 - 将
(click)事件添加到span中的项,因为它将是最后一个接收点击事件的元素。 - 在同一个
span中添加了$event.stopPropagation()
这应该绰绰有余。
