}
The code creates a Subject<void> and pipes it through the takeUntil() operator to create an Observable. The code then creates a Subscription and pipes the Observable through it. The Subscription then binds itself to the Subject<void>. The code then declares an input property called events. The code then initializes the Subscription and sets the input property to the Observable. The code then calls ngOnInit() and calls ngOnDestroy() when the component is destroyed.
Library: angular
import { Observable, Subject } from 'rxjs';
//Parent component
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next("something");
}
//Parent template
<child [events]="eventsSubject.asObservable()"> </child>
//Child component
private ngUnsubscribe: Subject<void> = new Subject<void>();
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.pipe(takeUntil(this.ngUnsubscribe)).subscribe((data) => {
//data = "something"
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}