// counter-imperative.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
@Component({
selector: 'app-counter-imperative',
template: {{count}} ,
})
export class CounterImperativeComponent implements OnInit, OnDestroy {
private count$ = new Subject();
private subscription: Subscription;
count = 0;
ngOnInit(): void {
this.subscription = this.count$.subscribe((value) => (this.count = value));
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
increment(): void {
this.count$.next(this.count + 1);
}
decrement(): void {
this.count$.next(this.count - 1);
}
}
// counter-declarative.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Component({
selector: 'app-counter-declarative',
template: {{count$ | async}} ,
})
export class CounterDeclarativeComponent implements OnInit {
private countSubject$ = new BehaviorSubject(0);
count$: Observable = this.countSubject$.asObservable();
ngOnInit(): void {}
increment(): void {
this.countSubject$.next(this.countSubject$.value + 1);
}
decrement(): void {
this.countSubject$.next(this.countSubject$.value - 1);
}
}
EditExport Pub: 12 Apr 2023 18:32