组件未收到指令事件

时间:2018-12-06 09:38:44

标签: angular-directive angular7

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

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

1 个答案:

答案 0 :(得分:0)

像这样更改debounceEvent属性的decarator

model = Sequential()
e = Embedding(input_dim=vocab_size2, input_length=22, output_dim=200, weights=[embedding_matrix2], trainable=False)
model.add(e)
model.add(LSTM(128, input_shape=(X_train.shape[1],200),dropout=0.2, recurrent_dropout=0.1, return_sequences=True))
model.add(LSTM(200, input_shape=(X_train.shape[1],200),dropout=0.2, recurrent_dropout=0.1, return_sequences=False))

model.add(Dense(y_train.shape[1],activation='sigmoid'))

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