【发布时间】:2018-11-12 15:37:01
【问题描述】:
情况
在mat-form-field 中,我有一个mat-select,当单击它时,会相应地显示mat-options,并在所有mat-options 的顶部进行过滤。
期望的结果
用户点击mat-select,然后出现mat选项。然后用户开始输入,然后看到他们想要的结果,因此他们按下键盘上的向下箭头并按 ENTER 以选择该选项。
Image of the current UI with Filter Active
问题
一旦用户单击<input> 开始过滤mat-options,“ENTER to select”功能将不再用于选择mat-options。
然而,如果用户没有点击进入<input> 开始过滤而只是使用箭头键导航然后按ENTER 选择,mat-option 将被正确选择。
当input 过滤器处于活动状态时,当用户在mat-option 上按ENTER 时,如何强制单击?
技术
• Angular 7.0.2
• @angular/material ^7.0.2
• 引导 ^4.1.3
input-filtered-select.component.ts
<mat-form-field>
<mat-select [placeholder]="placeholderMessage | titlecase" ngModel [required]="isRequired" name="filteredSelectControl" [(value)]="selectedValue">
<mat-option class="filter-input-option">
<input enterSelect type="text" class="form-control" placeholder="Type to filter..." [(ngModel)]="filterValue" name="filterValue" (ngModelChange)="filteredData = filterData(filterValue)" (click)="preventClose($event)" />
</mat-option>
<mat-option (click)="onSelect()" *ngFor="let data of filteredData" [value]="data">
{{ data.name }}
</mat-option>
<mat-option (click)="onAddNew()" *ngIf="filteredData.length === 0 && showNoOptionAddNew">Add new {{ filterSubject }}</mat-option>
<mat-option *ngIf="filteredData.length === 0 && showNoOptionNoDriver">New driver's can only be added by an admin</mat-option>
</mat-select>
<mat-error>{{ errorMessage }}</mat-error>
</mat-form-field>
我现在正在尝试什么
我正在尝试创建一个名为 enterSelect 的指令,该指令使用 mat-option ng-star-inserted mat-active 类查找 mat-option 并强制单击 HTMLElement,但是,目前这不起作用。这是我的代码:
enter-select.directive.ts
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[enterSelect]'
})
export class EnterSelectDirective {
selectedElement: HTMLElement;
targetElement: HTMLElement;
constructor() { }
/**
* @HostListener to click the POST button if the user
* presses the ENTER key - Allows for Shift+Enter for
* new line
* @param event keypress
* @returns false
*/
@HostListener('keydown', ['$event']) onkeydown(event) {
let e = <KeyboardEvent> event;
if (e.which === 13) {
this.selectedElement = (<HTMLElement>e.srcElement.closest('div').getElementsByClassName('mat-option ng-star-inserted mat-active')[0]);
console.log(this.selectedElement.click());
console.log('Enter clicked!!!');
e.preventDefault();
return false;
}
}
}
【问题讨论】:
标签: javascript angular angular-material