组件未收到指令事件 [英] Directive event not being received by the component

查看:44
本文介绍了组件未收到指令事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户搜索功能,在搜索字词字段上带有反跳指令:

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();
  }

}

该指令正确地发出事件,因为logger语句显示键入的字符串,但从未调用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

这篇关于组件未收到指令事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆