首页 > 解决方案 > 使用 Angular 清除按钮单击上的过滤器输入字段的机会

问题描述

首先,总的来说,我对 Angular 和 Web 开发非常陌生。此外,我的英语很烂,但我尽我所能清楚地表达自己。

我得到了以下场景:我的工具向用户显示了一个 mat-table,它上面有一个 textfilter 行。

textfilter 行是一个简单的输入字段,用于侦听将触发以下函数的 keyup 事件:

applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

这工作正常。现在我想让用户有机会通过按下旁边的“清除”按钮来清除输入字段。我不知道如何访问输入字段并通过打字稿更改其值(到“”)。

可以在这里使用 ViewChild 和 Element Ref 吗?

可能是一个非常愚蠢的问题,但在此先感谢。

标签: angularmat-table

解决方案


为什么在 angular2+ 的输入字段上使用 keyup 事件监听器?我会利用双向绑定的优势。这真的很强大。

看看我为你制作的沙盒:https ://codesandbox.io/s/icy-breeze-zcrcy

app.component.html:

<div style="text-align:center">
  <input
    class="form-check-input"
    type="text"
    name="filterInput"
    [(ngModel)]="inputData"
  />
  <button (click)="clearInput()">CLEAR INPUT</button>

  <div>
    Here is my inputData: {{ inputData }}
  </div>
</div>

app.component.ts:

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  public inputData: string = "";
  title = "CodeSandbox";

  clearInput() {
    this.inputData = "";
  }
}

并且不要忘记将FormsModule添加到您的app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

请记住,ngModel 是 FormsModule 的一部分。这就是为什么你必须将 FormsModule 导入你的 app.module.ts。


推荐阅读