问题
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>
It is supposed to call the method:
search(searchTerm: string): void {
console.log('Searching for ' + searchTerm);
}
The directive is implemented as:
@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();
}
}
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.
回答1:
Change the decarator of the debounceEvent property like this
@Output('appOnDebounce')
public debounceEvent: EventEmitter<any>;
Please see here the sample solution https://ng2-debounce-sample.stackblitz.io
来源:https://stackoverflow.com/questions/53648388/directive-event-not-being-received-by-the-component