Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Html string interpolation not seeing change from Angular's onPush strategy within observable

Using Angular 14, I have in the string template interpolation in the html. I am using ChangeDetectionStrategy.OnPush. When the ngOnInit() runs and subscribe observable gets the value, I am not seeing a change in the html when this.headerName = name; is set. How can I fix this and still use onPush?

        <div class="col-4 gx-5">
          <p>Corporate Name</p>
          <p>{{headerName}}</p>
        </div>
  @Component({
    selector: 'app-importer-main',
    changeDetection: ChangeDetectionStrategy.OnPush,
  ...
     ngOnInit(): void {
      this.apiService.consumeAgenciesApi().subscribe((el) => {
        const {
          name,
        } = el[0];
  
        this.headerName = name;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

OnPush works great when you follow the reactive approach, without subscribing manually to observables, pipe the value and then use the async pipe like the following:

name$!: Observable<string>;

ngOnInit(): void {
  this.name$ = this.apiService.consumeAgenciesApi().pipe(
   map(response) => response[0]?.name
  );
}
<!-- FYI, ng-container is not render in the DOM -->
<ng-container *ngIf="name$ | async as headerName"> 
 <div class="col-4 gx-5">
   <p>Corporate Name</p>
   <p> {{ headerName }} </p>
 </div>
</ng-container>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading