RxJS Observables
Written By: Avinash Malhotra
Updated on
RxJS Observables are used for manually change detection. They also improve performance as emit values without changing the reference of object.
Observables will notice the change without creating reference. So we can subscribe to the Observables and on change manually run change detector inside subscribe method to change view.
Use Observables
To use RxJS Observables, import BehaviorSubject in component. Observables can change the value but the new reference is not created.
<!--app.component.html-->
<h1>{{title}}</h1>
<button (onclick)="changeTitle()">Click</button>
<p>{{data._value}}</p>
<!--app.component.ts-->
import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-root',
standalone: true,
imports: [ ],
templateUrl: './app.component.html',
styleUrl: './app.component.css',
changeDetection:ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
title = 'myApp';
x=0;
data:any;
ngOnInit(){
this.x=10;
this.data=new BehaviorSubject(this.x);
}
changeTitle(){
this.x=this.x+this.x;
this.data.next(this.x);
}
}