我有一个搜索输入,我只想在用户触摸或输入输入字段时触发this.searchProperties.emit,我不想在视图输入之后触发它。我只想在用户触摸或输入输入字段时发出。
当前的问题是,它在视图初始化后调用发出。谢谢你的任何想法或帮助。
html代码
<mat-form-field id="property-list-filter" appearance="fill">
<mat-label style="font-size:12px">Filter properties</mat-label>
<input matInput #searchInput placeholder="Ex. Property ID" #input>
</mat-form-field>ts代码片段
@ViewChild('searchInput') searchInput: ElementRef;
ngAfterViewInit() {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator
fromEvent<any>(this.searchInput.nativeElement, 'keyup')
.pipe(
map((event) => event.target.value),
startWith(''),
debounceTime(500),
distinctUntilChanged(),
switchMap(async (search) => {
this.searchProperties.emit(this.searchInput.nativeElement.value.trim().toLowerCase())
})
)
.subscribe({ complete: noop });
}发布于 2022-11-29 10:04:59
首先,从管道中删除startWith。它在第一次初始化时触发发出。
为了跟踪input事件,您必须像这样使用Angular event binding来听它:
<input (input)="onInput()"/>在你的ts文件中:
onInput(){
...
}为了倾听用户的输入-触摸,您可以以同样的方式侦听focus事件或其他适合您需要的事件。
此外,我建议您使用角的ReactiveForms API来管理输入状态。你会发现你所需要的一切都是明智和被动的。这是一个链接。
发布于 2022-11-29 10:26:56
我建议你使用ngModel和ngModelChange
<mat-form-field id="property-list-filter" appearance="fill">
<mat-label style="font-size:12px">Filter properties</mat-label>
<input matInput [(ngModel)]="input variable" (ngModelChange)="changeHandlerFunction()" placeholder="Ex. Property ID" #input>
</mat-form-field>https://stackoverflow.com/questions/74612135
复制相似问题