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 :

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>

Leave a Reply