组件未接收到指令事件
Directive event not being received by the component
我有一个用户搜索功能,在搜索词字段上有一个去抖动指令:
<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 {}
方法。
像这样更改 debounceEvent 的修饰符属性
@Output('appOnDebounce')
public debounceEvent: EventEmitter<any>;
请在此处查看示例解决方案https://ng2-debounce-sample.stackblitz.io
我有一个用户搜索功能,在搜索词字段上有一个去抖动指令:
<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 {}
方法。
像这样更改 debounceEvent 的修饰符属性
@Output('appOnDebounce')
public debounceEvent: EventEmitter<any>;
请在此处查看示例解决方案https://ng2-debounce-sample.stackblitz.io