在角材料中输入keypress事件中获取价值

时间:2018-08-13 10:04:57

标签: angular events angular-material mat

根据Angular Materiallink to the example中的示例,尝试使用清除按钮创建输入,我想要的是在key enter事件上获取输入值。

HTML:

<mat-form-field>
  <input matInput (keydown.enter)="applyFilter($event)" placeholder="Search" 
   name="search" [(ngModel)]="searchValue">
  <button mat-icon-button matSuffix aria-label="Clear" (click)="clearSearch()">
    <mat-icon>close</mat-icon>
  </button>
</mat-form-field>

TS:

  applyFilter(event: any) {
      console.log(JSON.stringify(event)); 
  }

打印事件内容时控制台的结果:

{"isTrusted":true}

2 个答案:

答案 0 :(得分:2)

您只需要在 event.target.value 方法中使用 applyFilter() 来获取值。

applyFilter(event: any) {
  console.log(event.target.value); 
}

链接到StackBlitz Demo

答案 1 :(得分:1)

我不熟悉Material Design中组件的这种特定情况,但是注释中的建议是传统的实现方法。
MD组件可能会因事件而中断,因此您可以尝试将值手动传递给函数。像这样的东西:

<mat-form-field>
  <input matInput #txtVal (keydown.enter)="applyFilter(txtVal.value)" placeholder="Search" 
   name="search" [(ngModel)]="searchValue">
  <button mat-icon-button matSuffix aria-label="Clear" (click)="clearSearch()">
    <mat-icon>close</mat-icon>
  </button>
</mat-form-field>

TS:

applyFilter(val: string) {
 console.log(val); 
}

#txtVal只是输入字段中的局部变量,因此我们将其值手动传递给函数。

相关问题