我正在尝试使用 RxJS 中的
viewChild
信号和 fromEvent
运算符来跟踪 Angular 模板中元素上的点击事件:
@Component({
selector: "app-example",
standalone: true,
template: `
<button #myButton>click me</button>
Last clicked: {{ lastClick() }}
`,
})
export class ExampleComponent {
buttonRef = viewChild("myButton", { read: ElementRef });
buttonEl = computed(() => this.buttonRef()?.nativeElement);
lastClick = toSignal(
fromEvent(this.buttonEl(), "click").pipe(map(() => Date.now()))
);
}
但是我收到以下错误:
TypeError: target is undefined
。
如何确保
this.buttonEl()
的值不是undefined
?
我无法在
static: true
信号选项中使用 viewChild
,就像我可以使用 @ViewChild
装饰器一样。我也无法在注入上下文之外使用 viewChildFn()
。
您可以使用
toObservable
中的 @angular/core/rxjs-interop
将 viewChild
信号转换为 Observable
,然后在拥有元素后使用 switchMap
运算符切换到监听单击事件。
import { Component, ElementRef, computed, viewChild } from "@angular/core";
import { toObservable, toSignal } from "@angular/core/rxjs-interop";
import { fromEvent, map, switchMap } from "rxjs";
@Component({
selector: "app-example",
standalone: true,
template: `
<button #myButton>click me</button>
Last clicked: {{ lastClick() }}
`,
})
export class ExampleComponent {
buttonRef = viewChild("myButton", { read: ElementRef });
buttonEl = computed(() => this.buttonRef()?.nativeElement);
lastClick = toSignal(
toObservable(this.buttonEl).pipe(
switchMap((el) => fromEvent(el, "click").pipe(map(() => Date.now())))
)
);
}