Directive event not being received by the component

大城市里の小女人 提交于 2019-12-11 15:37:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!