英文:
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:
<custom-input (altered)="inputChanged($event)"
...
>
@Output()
public changed: EventEmitter<string> = 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('t')
-> 100ms
-> inputChanged('te')
-> 200ms
-> inputChanged('tes')
-> 50ms
-> inputChanged('test')
-> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论