本文介绍了组件未收到指令事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用户搜索功能,在搜索词字段上有一个 debounce 指令:
I have a user search feature with a debounce directive on the search term field:
<mat-form-field>
<input matInput [(ngModel)]="searchTerm" (appOnDebounce)="search($event)" placeholder="Search..." autocomplete="off">
</mat-form-field>
它应该调用该方法:
search(searchTerm: string): void {
console.log('Searching for ' + searchTerm);
}
指令实现为:
@Directive({
selector: '[ngModel][appOnDebounce]'
})
export class DebounceDirective implements OnInit, OnDestroy {
@Output()
public debounceEvent: EventEmitter<string>;
@Input()
public debounceTime = 300;
private isFirstChange = true;
private subscription: Subscription;
constructor(public model: NgControl) {
this.debounceEvent = new EventEmitter<string>();
}
ngOnInit() {
this.subscription = this.model.valueChanges
.debounceTime(this.debounceTime)
.distinctUntilChanged()
.subscribe((modelValue: string) => {
if (this.isFirstChange) {
this.isFirstChange = false;
} else {
console.log(modelValue);
this.debounceEvent.emit(modelValue);
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
指令正确地发出事件,因为记录器语句显示输入的字符串,但 search(searchTerm: string): void {}
方法从未被调用.
The directive correctly emits the events as the logger statement shows the typed in string, but the search(searchTerm: string): void {}
method is never called.
推荐答案
像这样更改 debounceEvent 属性的 decarator
Change the decarator of the debounceEvent property like this
@Output('appOnDebounce')
public debounceEvent: EventEmitter<any>;
请在此处查看示例解决方案 https://ng2-debounce-sample.stackblitz.io
Please see here the sample solution https://ng2-debounce-sample.stackblitz.io
这篇关于组件未收到指令事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!