0

I want to re-call my ngAfterViewInit since it is responsible for changing my dom's style. So if my components data changes my component gets updated but my styles are not applying on the new data. Here in the below code my component which is responsible for showing some product information is subscribed to router params observable. So if I change the route params than information gets changed without rerunning my component but styles are not applied since component is not initiated again so afterViewInit is not called again. Here my code

ngOnInit() {
    this.currentRoute.params.subscribe((params) => {
      this.productId = params['productId'];
      this.category = params['category'];
      this.productService.getSingleProduct(this.category, this.productId); //fetching product data
    });
  }
ngAfterViewInit(){
   // some codes to change the dom styles
}

So how I can re-call my ngAfterViewInit if I get new sets of product data?

**Important points----

1- I can't put my ngAfterViewInit code to params subscription because that code depends on dynamic contents.

2- I know I can call ngAfterViewInit method in ngAfterViewChecked lifecycle hook which works just fine but I think I am calling those functions too often.

Janitha Rasanga
  • 1,010
  • 1
  • 11
  • 20
sahil aktar
  • 101
  • 10
  • Can you be more specific about why you cant put your ngAtferViewInit code inside the params subscription? What are these dynamic contents your code depends on? – RonCG Oct 09 '20 at 15:31
  • Because i am looping over some images which i am getting from backend and set some style on the active image like some border on the image which is on the main frame..so i will only get those images divs on afterViewInit only. – sahil aktar Oct 09 '20 at 16:26
  • It seems to me that you should be able to place the code that gets the images in a function, use that function in ngAfterViewInit, and then call the same function in the params subscription. Is there a particular reason this approach wouldnt work? – RonCG Oct 10 '20 at 13:02
  • that wouldn't work correctly because my params subscription is on ngOnInit lifecycle hook and in onInit lifecycle hook i can't work with the dom which is rendered after i get data from backend..by the way i solved that problem by using ngClasses since i was only adding some classes to the selected image therefor i don't have to use ngAfterViewInit at all. – sahil aktar Oct 11 '20 at 05:42

0 Answers0