如何在mat-form-field的输入中获取点击事件?

时间:2019-03-26 12:35:58

标签: angular angular-material

当我点击自动完成按钮时,我想清除选择的选项:

  <mat-form-field class="example-full-width" (click)="clear()" appearance="outline">
    <input matInput placeholder="State" aria-label="State" 
    [matAutocomplete]="auto" [formControl]="stateCtrl">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let state of filteredStates | async" 
      [value]="state.name">
      </mat-option>
    </mat-autocomplete>
  </mat-form-field> 

但是,即使您在下面稍稍按一下,也会单击。(表格中有空白)

Example showing input clear by clicking outside

2 个答案:

答案 0 :(得分:2)

(click)="clear()"标签上使用<input>
而不在mat-form-field标签上使用。

styles.css中添加以下内容以覆盖CSS,并使input标签覆盖容器的整个高度。

.mat-form-field-appearance-outline .mat-form-field-infix {
  padding: 0 !important;
  border-top: 0;
}
input.mat-input-element {
  padding: 1.84375em 0 1em 0;
}

Stackblitz Demo - only clear from input click

答案 1 :(得分:0)

我找到了一种无需更改样式的方法,只需将事件添加到mat-form-field-flex

document
  .querySelectorAll('p-autocomplete .mat-form-field-flex')[0]
  .addEventListener('click', (ev) => this.clear(ev));