【问题标题】:Directive event not being received by the component组件未接收到指令事件
【发布时间】:2018-12-07 13:58:14
【问题描述】:

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

<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 {} 方法。

【问题讨论】:

    标签: angular-directive angular7


    【解决方案1】:

    像这样更改 debounceEvent 属性的说明符

    @Output('appOnDebounce')
    public debounceEvent: EventEmitter<any>;
    

    请在此处查看示例解决方案https://ng2-debounce-sample.stackblitz.io

    【讨论】:

    • 有趣的是,我的VSCode IDE 中的tslint 抱怨[tslint] @Outputs should not be renamed (no-output-rename) (property) DebounceDirective.debounceEvent: EventEmitter&lt;string&gt; `
    • 相反,我重命名了我的输出变量,它也可以正常工作@Output() public appOnDebounce: EventEmitter&lt;string&gt;;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2019-09-11
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多