angular - 使用 Angular 清除按钮单击上的过滤器输入字段的机会
问题描述
首先,总的来说,我对 Angular 和 Web 开发非常陌生。此外,我的英语很烂,但我尽我所能清楚地表达自己。
我得到了以下场景:我的工具向用户显示了一个 mat-table,它上面有一个 textfilter 行。
textfilter 行是一个简单的输入字段,用于侦听将触发以下函数的 keyup 事件:
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
这工作正常。现在我想让用户有机会通过按下旁边的“清除”按钮来清除输入字段。我不知道如何访问输入字段并通过打字稿更改其值(到“”)。
可以在这里使用 ViewChild 和 Element Ref 吗?
可能是一个非常愚蠢的问题,但在此先感谢。
解决方案
为什么在 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。
推荐阅读
- flutter - 颤振发布运行 build_runner 构建失败
- next.js - TypeError:无法解构“未定义”或“空”的属性“请求”
- node.js - 日期过滤在 mongoldb 中不起作用
- python-3.x - 如何显示尊重其相对大小的图像?
- android - 解释这个 Bash 脚本
- python - 我想控制卷积神经网络中的步幅,但我不知道如何写步幅
- regex - 验证数据后如何从 xml 文件中获取数据?
- c# - Visual Studio调试在mvc中上传文件时立即停止?
- python-3.x - 如何使用 python 在时间为“00:00:00”时将 timedelta 添加到 datetime
- r - 具有多个变量的ggplot,如何使用它?