This is the functionality of the component utilizing EventEmitter:
import { Component, Output, EventEmitter } from "@angular/core";
@Component({
selector: "app-my-component",
template: ` <button (click)="clickEvent($event)">Foo</button> `
})
export class MyComponent {
@Output()
onClick: EventEmitter<string> = new EventEmitter<string>();
clickEvent(): void {
this.onClick.emit("something that comes from my.component.ts");
}
}
@Component({
selector: "app-root",
template: `
<h1>Title inside app component.</h1>
<app-my-component (onClick)="doSomething($event)"></app-my-component>
`
})
export class AppComponent {
doSomething(foo) {
console.log(foo);
}
}
Is there a way to achieve similar functionality using an RXJS observable?
I'm attempting the following approach:
import {
Component,
ElementRef,
ViewChild,
AfterViewInit,
Output
} from "@angular/core";
import { Observable, fromEvent } from "rxjs";
import { tap } from "rxjs/operators";
@Component({
selector: "app-my-component",
template: ` <button #btn>Foo</button> `
})
export class MyComponent implements AfterViewInit {
@Output()
onClick: Observable<string>;
@ViewChild("btn", { static: true }) buttonRef: ElementRef<HTMLButtonElement>;
foo$: Observable<?>;
ngAfterViewInit() {
this.foo$ = fromEvent(this.buttonRef.nativeElement, "click").pipe(
tap((e) => e.stopPropagation())
);
}
// what should be returned here?
onClick(): Observable<?> {
return this.foo$
}
}
@Component({
selector: "app-root",
template: `
<h1>Title inside app component.</h1>
<app-my-component (onClick)="doSomething(event$)"></app-my-component>
`
})
export class AppComponent {
doSomething(foo) {
console.log(foo);
}
}
Should RXJS be used for handling a button click event?
I have read some outdated blog posts and couldn't find a comprehensive example of handling a button click event. Any guidance on this matter with a practical example would greatly assist in understanding the concept.