Vlad_Gesin
Vlad_Gesin

Reputation: 138

Angular Change Detection On Push

I am trying to invoice change detection on the changing params page. After that, I get recipe JSON from DB. Why my code doesn't invoice component change detection when I create a new Subscription in the ngOnInit?

import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription, switchMap } from 'rxjs';
import { RecipesApiService } from '../../../services/recipes/recipes-api.service';
import { IRecipeApi } from '../../../services/recipes/recipes';

@Component({
  selector: 'app-recipe-page',
  templateUrl: './recipe-page.component.html',
  styleUrls: ['./recipe-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RecipePageComponent implements OnInit, OnDestroy {
  recipe!: IRecipeApi;
  private sub$!: Subscription;

  constructor(
    private route: ActivatedRoute,
    private recipesApiService: RecipesApiService
  ) {}

  ngOnInit(): void {
    this.sub$ = this.route.params
      .pipe(
        switchMap((params) => {
          return this.recipesApiService.getRecipeApiById(params['id']);
        })
      )
      .subscribe((recipe) => {
        this.recipe = recipe;
      });
  }

  ngOnDestroy() {
    this.sub$.unsubscribe();
  }
}

Upvotes: 1

Views: 1071

Answers (1)

TotallyNewb
TotallyNewb

Reputation: 4790

Why would it? With ChangeDetectionStrategy.OnPush you have to manually invoke change detection. That's the whole point of using it. In your code you don't do so, hence the change detection is not invoked.

Read more about change detection in the official docs here, or refer to one of the multiple tutorials available on the web.

Upvotes: 1

Related Questions