The ngOnInit lifecycle hook is not triggered by the Angular routerLink

In the component.ts file, you will find the ngOnInit function as shown below:

ngOnInit() {
      this.locationService.getLocation().subscribe( locations => {
      this.locations = locations;
    });
  }
<a [routerLink]="['/locations-list']">

While using a [routerLink] to navigate to the above component, it loads the view but does not trigger the ngOnInit method. However, refreshing the page resolves the issue. Is there a solution for this problem?

I have previously used href for navigation which always worked fine with the above method, but it was slow. This led me to switch from href to [routerLink].

The following is the content of the component.html file including the view:

                <div class="table-responsive">
                  <table class="table">
                    <thead class=" text-primary">
                      <th>
                        Location Name
                      </th>

                    </thead>
                    <tbody *ngIf="locations?.length > 0">
                      <tr *ngFor="let location of locations">
                        <td *ngIf="location.verified != false">
                          {{location.locationName}}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

Answer №1

After a component has been instantiated, the ngOnInit() method is called only once and not when the route changes. To be notified about route changes, you have the option to inject the router and subscribe to its events or params.

ngOnInit() {
     this.route.params.subscribe((params: any) => {
       if(params) //your code
    });
}

Answer №2

When the parameter of the router is modified, the base route remains constant. As a result, the ngOnInit method is not triggered. To handle this situation, you can subscribe to the route event.

ngOnInit() {
     this.route.params.subscribe(
     params => { 
            // Your custom code here
     });
  }

Answer №3

Give this a shot

// when clicked, execute the HyperLink function
    (click)="HyperLink()"
// in the Typescript file 
    HyperLink(){
       window.open('/locations-list');  
   }

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

Receive notifications from a JSON URL in your area

In my Ionic app, I have integrated a feature to display flight schedules using a JSON data API. The goal is to notify users through a bell icon about the status of the flight, whether it's arrival, delay, or landed. To achieve this, I have installed L ...

Using Typescript to incorporate Next.js on Firebase Functions

I'm currently working on deploying a Next.js application to Firebase Functions. import next from 'next' import {https} from 'firebase-functions' const server = next({ dev: process.env.NODE_ENV !== 'production', conf: ...

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

Solving the issue of loading Ember Initializers during the transition to TypeScript

While following the ember quick start tutorial, I attempted to switch from Javascript to Typescript. Converting the .js files to .ts files resulted in an error with the ember-load-initializers import. The application is unable to run until this issue is re ...

Access your Angular 2 application on an external device during the development process

Is there a way to view your app in an external device like a cell phone web browser, instead of just running npm start and viewing it in your desktop browser? ...

What is the best way to activate an input field in react-select?

Currently, I am working on a dropdown feature using react-select and have encountered some issues that need to be addressed: 1) The input field should be focused in just one click (currently it requires 2 clicks). 2) When the dropdown is opened and a cha ...

I am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

Angular 11 - Binding Data to an Array Element

Currently, I am attempting to apply data-binding to specific properties of an element categorized as Ripe: export interface Ripe{ version: string; data_call_status: string; cached: boolean; data: { is_less_specific: boolean, ...

You may encounter an error stating "Property X does not exist on type 'Vue'" when attempting to access somePropOrMethod on this.$parent or this.$root in your code

When using VueJS with TypeScript, trying to access a property or method using this.$parent.somePropOrMethod or this.$root.somePropOrMethod can lead to a type error stating that Property somePropOrMethod does not exist on type 'Vue' The defined i ...

"Encountering a 404 Error when attempting to refresh an Angular 13 application hosted on an Apache

I have developed a prototype web application and now need to deploy it on an Apache server running Ubuntu OS. After building the web app, I hosted it on my local machine for testing purposes. I have configured the .htaccess file as follows: RewriteEngine ...

MatDialog displaying no content

I found this tutorial on how to implement a simple dialog. The issue I'm facing is that the dialog appears empty with no errors in the console. Even after making changes to my dialog.component.html or dress-form.ts, nothing seems to reflect in the o ...

Localization & Internationalization in Angular 6 CLI for enhancing multi-language functionality

Our Application is built on Angular 6 and we are looking to incorporate multilingual support. Please advise on how we can enable localization and internationalization in Angular 6. This pertains specifically to the Angular 6 version. ...

Ways to set a background image for two separate components in Angular

Trying to figure out how to integrate this design: The challenge lies in having a background image that spans across the navbar and the content below it. Currently, the code separates the navbar component from the content component, making it tricky to ac ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

Encountering an error when invoking a web API controller from a service in Angular 2

I am currently following an Angular quick start tutorial that focuses on the Hero tutorial provided on the Angular2 website. The tutorial runs smoothly for me as it binds static array data and allows for CRUD operations. However, my goal now is to understa ...

Implementing the react-i18next withNamespaces feature in Ant Design forms

I'm a newcomer to i18next and TypeScript, and I'm trying to translate an antd form using withNamespaces. export default withNamespaces()(Form.create()(MyComponent)); Encountering the following error: Argument of type 'ComponentClass< ...

Manipulating strings in Angular using property binding

Is there a way to concatenate the following two statements that work individually? <app-output [warnMessage]="myvalue | number:'1.0-1'"></app-output> <app-output [warnMessage]="'TEXT01' | translate"></app-output&g ...

Angular 2 Twitter integration plugin

I attempted to integrate a Twitter timeline into my Angular 2 application. I followed the instructions provided on , and this is what I ended up with: <a class="twitter-timeline" href="https://twitter.com/TwitterDev">Tweets by TwitterDev</a> & ...

The error message states that the property 'registerUser' is not found on the class 'UserController'

In the controller file, I exported two functions (registerUser and loginUser) as default. No errors were thrown at that stage, but when attempting to access the routes, an error occurred stating - Property 'registerUser' does not exist on type &a ...

Using ReactJS with Typescript: attempting to interpret a value as a type error is encountered (TS2749)

Currently, I am working on coding a ReactJS class using Typescript and Material-ui in a .tsx file. In one of the custom components that I have created, I need to establish a reference to another component used within this custom component. export class My ...