Search code examples
angulartypescriptngxs

Angular @Input not working on browser back and component won't render


On parent component, I have a product list that I get from store:

// ...
ngOnInit() {
  this.products$.subscribe(products => {
     this.products = products;
  })
}
// ...
<!-- ... -->
  <ng-container *ngIf="products">
    <product-list [products]="products"></product-list>
  </ng-container>
<!-- ... -->

And on child product-list:

// ...
@Input() products: IProduct[];
// ...
<!-- ... -->
  <div *ngFor="let product of products">
    <product-card [product]="product">
  </div>
<!-- ... -->

And than I have each product-card show product.image.

The problem I'm facing is, when ever I land on this page, I'm able to view all products, but when I click on something on the page and than browser back to this page, the product-list is not displayed.

I don't have any errors in console and I can confirm that the child component is receiving the data on the second render adding debug points in debug console.

Why is my child component only displayed on first render? Not even refresh will work. Only when I navigate to the page by entering the url in browser will I get the same component to display. Thanks in advance.


Solution

  • Turns out, my top component did not implement OnDestroy and the component was lingering after redirect. I solved the problem by doing the following:

    @Component({ /* ... */ })
    class topComponent implements OnInit, OnDestroy {
      // ...
      private readonly destroy$ = new Subject<void>();
    
      // ...
      ngOnDestroy() {
        this.destroy$.next();
        this.destroy$.complete();
      }
    }
    

    The destroy$.[METHOD] will let go of any subscribed observables that you have subscribed by using this.[SELECT].pipe(takeUntil(this.destroy$)).subscribe(...). Pretty neat.

    Thanks for all your help!