Angular 仅在一定时间内不调用方法时触发事件。

huangapple go评论69阅读模式
英文:

Angular Emit event only if method does not get called for a certain timespan

问题

我有一个输入字段,一旦输入发生更改,就会调用inputChanged方法。它看起来像这样:

<custom-input (altered)="inputChanged($event)"
              ...
              >
@Output()
public changed: EventEmitter<string> = new EventEmitter();

...

public inputChanged(value: string): void {
    this.changed.emit(value + ...)
}

我试图实现的是,仅当最后一次调用inputChanged距今已有1000毫秒时,才触发this.changed.emit(value + ...)

因此,序列可以如下所示。

inputChanged('t')
-> 100ms
-> inputChanged('te')
-> 200ms
-> inputChanged('tes')
-> 50ms
-> inputChanged('test')
-> 1000ms
-> this.changed.emit(value + ...)

我找到了像rxjs中的debounceTime这样的东西,但不知道如何在我的上下文中使用它,因为我不被允许修改输入字段组件本身。实现必须在使用输入字段的组件中进行。

有人能帮助我吗?

FYI: 我正在使用Angular 15。

英文:

I have an input field that calls the method inputChanged as soon as the input changes.
It looks like this:

&lt;custom-input (altered)=&quot;inputChanged($event)&quot;
              ...
              &gt;
@Output()
public changed: EventEmitter&lt;string&gt; = new EventEmitter();

...

public inputChanged(value: string): void {
    this.changed.emit(value + ...)
}

What I am trying to achieve is to only trigger this.changed.emit(value + ...) if the last time inputChanged has been called is more than 1000ms ago.

So the sequence could look like this.

inputChanged(&#39;t&#39;)
-> 100ms
-> inputChanged(&#39;te&#39;)
-> 200ms
-> inputChanged(&#39;tes&#39;)
-> 50ms
-> inputChanged(&#39;test&#39;)
-> 1000ms
-> this.changed.emit(value + ...)

I have found stuff like debounceTime in rxjs but I don't know how to use this in my context as I am not allowed to alter the input field compoment itself. The implementation has to be in the component that uses the input field.

Can anybody help me here?

FYI: I am using Angular 15.

答案1

得分: 1

有趣的事实:一个常规的Observable可以作为@Output()来使用,而不是EventEmitter

在你的组件中,引入一个Subject来传递值,然后暴露一个使用debounceTime来控制发射的Observable

class YourComponent {

  private value$ = new Subject();

  @Output() changed = this.value$.pipe(debounceTime(1000));

  public inputChanged(value: string): void {
      this.value$.next(value + ...)
  }

}

这里有一个小的StackBlitz演示。

英文:

Fun fact: a regular Observable can be used as an @Output() instead of an EventEmitter.

In your component, introduce a Subject to push values through, then expose an Observable that uses debounceTime to control emissions.

class YourComponent {

  private value$ = new Subject();

  @Output() changed = this.value$.pipe(debounceTime(1000));

  public inputChanged(value: string): void {
      this.value$.next(value + ...)
  }

}

Here's a little StackBlitz demo.

huangapple
  • 本文由 发表于 2023年2月23日 20:22:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定