1

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();
  }
}

1
  • Would be nice to see your template. However, you can manually execute change detection injecting ChangeDetectorRef in your constructor and using it like this.cd.detectChanges(); Commented May 27, 2022 at 10:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes I know it, the question is how can I invoke it?
Why does the Subscription won't invoke it?
Everything is explained in the linked docs, even with an example. You inject the ChangeDetectorRef in the constructor, and call .markForCheck() when you want to run change detection - in your case inside the subscription, after you updated the value of this.recipe.
I thought the sub$ will invoke it.. well i got wrong about it.
The documentation is something publicly available and anyone who reads it, might get more doubts hence the question was asked.this answer is not simplying it,just linking resources

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.