Issue with Angular @Input when navigating back in browser causing component to not render

Within the parent component, I am fetching a list of products from the store:

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

On the child component product-list:

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

Each product-card should display product.image.

The issue I am encountering is that upon initially landing on the page, all products are visible. However, if I navigate away from the page and return, the product-list does not display.

There are no error messages in the console, and I have confirmed that the child component is receiving the data upon the second render by adding debug points in the console.

Why is my child component only visible on the initial render? Even refreshing the page does not resolve the issue. The component will only display if I navigate to the page directly via the URL. Thank you in advance.

Answer №1

When navigating back, ngInit may not be triggered. In this case, utilize ActivatedRoute and set up a subscription to params:

constructor(route: ActivatedRoute) {
  route.params.subscribe(data => {

  });
}

To subscribe to multiple observables simultaneously, consider using combineLatest. https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest

Answer №2

It turns out that my main component was not implementing OnDestroy, causing it to linger after a redirect. I was able to resolve this issue by taking the following steps:

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

  // ...
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

Using destroy$.[METHOD] allows you to unsubscribe from any observables that were subscribed to using

this.[SELECT].pipe(takeUntil(this.destroy$)).subscribe(...)
. Pretty cool, right?

Thank you for all the assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What alternative approach can be used to substitute initEvent in typescript?

I am interested in manually triggering a MouseEvent in typescript, but I have discovered that the initEvent method is deprecated. var clickEvent =document.createEvent('MouseEvent'); clickEvent.initEvent('mouseup',true,true); https://i. ...

Utilizing the 'create' function in sqlite each time I need to run a query

I've been diving into SQLite within the Ionic framework and have pieced together some code based on examples I've encountered. import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-a ...

How can I adjust the padding and width attributes of the mat-menu in Angular 5

Today, I am struggling with a piece of code. Whenever I click on the Details button, it is supposed to open a mat-menu. However, for some reason, I cannot seem to adjust the padding or width of the menu: <div id="box-upload" [hidden]="hiddenBoxUpload" ...

How Angular Router deals with "/" in a route parameter

I've been working on an Angular project with routing, focusing on a route structure like the one below. { path : 'preview/:Id', loadChildren : () => import('./path/preview/preview.module').then( m => m.Preview ...

Adding data-attributes to a Checkbox component using inputProps in React

Utilizing Fabric components in React + Typescript has been a breeze for me. I have been able to easily add custom attributes like data-id to the Checkbox component, as documented here: https://developer.microsoft.com/en-us/fabric#/components/checkbox Howe ...

The functionality of Angular Custom Validation using Directive is experiencing issues within the ng-change event

I have created a custom validator using directives to validate email addresses. The validation is triggered by a method called on ng-change, but the validation only displays on the second change of the input. <textarea id="txtEmail" name=&qu ...

Unlock the Power of EmailJS with Vue.js 2 and TypeScript

I couldn't find a similar issue online, so here's my problem. I'm trying to create a form for receiving contact from an app using Vue.js 2 and TypeScript. Here is my code: <form ref="form" class="form-data" @submit.pr ...

What is your approach to organizing the HTTP requests in your Angular 2+ application?

I'm looking for suggestions on how to better organize my API calls within my services. How have you structured your API calls? Do you centralize all API calls for the entire application in one dedicated service? Do you create an HTTP folder and sepa ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...

Instructions for making a vertical arbitrary line on a financial graph

I came across this example on a website and it's functioning perfectly. The code creates a vertical line at the specified index location when x and y values are passed separately. example() { var originalLineDraw = Chart.controllers.line.prototype ...

Attempting to retrieve a file from the database with the utilization of Angular 5 and ASP.NET Core

I've been struggling with downloading a file from the database using its unique identifier. Can anyone provide guidance on what steps are necessary to achieve this successfully? The FileUpload table contains the following columns pertaining to the fi ...

Using Required and Partial with an Array of Generic Types

I'm currently working with the following types: interface Color { color: string } type DarkerColor<T> = T & Color & { darker: string } type ColorInfo<T> = DarkerColor<T> & { hue: number luminance: number opacity ...

Filter the angular accordion by passing a simple array value into the input

I am looking to filter my array of accordion items based on the value of the question matching the input I provide. I have tried using the filter method for this. this.accordionItems = [ { "topic":"polizze", " ...

jester: constantly jest navigator's mock & check against userAgent/vendor

Purpose: Need to iterate through different combinations of the userAgent Simulate navigator behavior Execute the test Observation: I simulated the navigator.userAgent, simulation works as planned, first test executes as expected Second simulation is per ...

Using TypeScript to work with JSON fields that include the '@' symbol

While working on an Angular project with TypeScript, I am facing a challenge of displaying certain JSON fields obtained from a POST request to the user. One of the fields begins with the '@' symbol, which is a reserved word in Angular causing th ...

The Angular 5 lifecycle hook ngOnChanges is triggered just once in a child component

I am struggling with syncing a child component containing complex input (such as chart data) with the API response received in the parent component in Angular 5. I am using the @Input() decorator to pass the chart data from the parent to the child componen ...

What is the process for combining an object and a primitive type to create a union type?

Having a tricky time with Typescript and finding the correct typing for my variable. What seems to be the issue? The variable selected in my code can either be of type DistanceSplit or number. I have an array that looks like this: [-100, DistanceSplit, D ...

Angular lifecycle event

When using the Firebase JS SDK in an Angular project and implementing lifecycle hooks, such as afterViewInit, I noticed that the console message repeats infinitely. How can I ensure that the message only appears once in the console? Thank you for any help ...

Is that possible to prevent the use of the & symbol in Angular 4 HTTP requests?

Using an HTTP request to save data in my database. The code snippet I used is: const form = '&inputdata=' + myinput + '&rf_date=' + rf_date; return this.http.post(this.rootUrl, form, {headers : this.reqHeader}); In thi ...

Angular2 application encounters issue with target attribute being overlooked by Chrome

I am trying to implement a link in an iframe following the instructions on W3Schools: <iframe height="300px" width="100%" src="demo_iframe.htm" name="iframe_a"> </iframe> <p><a href="http://www.w3schools.com" target="iframe_a">W3S ...