Angular 7's URL updates, but no other actions take place

I am new to posting here and feeling quite desperate. Currently, I am working with Angular 7 and facing an issue. The problem arises when I manually enter the desired URL, everything works perfectly. However, when I use RouterLink by clicking a button, the URL changes but the page does not respond. Interestingly, after reloading the page by pressing F5, the new URL works fine, indicating that it is not a URL routing problem.

At the moment, I have only implemented the routerLink in two buttons in the cities-nav section for testing purposes. Additionally, I have added a temporary one in the app-component.html as a backup solution, but it also does not work.

There are no errors shown in the console. Moreover, I have a console.log within the onInit function of the cities-nav component, which triggers when the web page loads for the first time, but not when using routerLink.

I have also attempted to execute a method with a (click) event, but even that does not work.

Here is my code:

My app.component.html:

<div style="text-align:center">
<nav>
<a routerLink="/">Go home</a>
</nav>
</div>
<router-outlet></router-outlet>

This is my app-routing.module:

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { CitiesNavComponent } from './cities-nav/cities-nav.component';

const routes: Routes = [
  { path: "", redirectTo: "cities/Madrid", pathMatch: "full" },
  { path: "cities/:name", component: CitiesNavComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

This is my cities-nav.component.html:

    <div class="container">
  <div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
    <header class="mdl-layout__header">
      <div class="mdl-layout__header-row">
        <span *ngIf="cityName" class="mdl-layout-title">{{this.cityName}}</span>
        <div class="mdl-layout-spacer"></div>
      </div>
    </header>
    <div class="mdl-layout__drawer">
      <span class="mdl-layout-title">Cities</span>
      <nav class="mdl-navigation">
        <a class="mdl-navigation__link" routerLink="/cities/Madrid" routerLinkActive="active">Madrid</a>
        <a class="mdl-navigation__link" routerLink="/cities/Barcelona">Barcelona</a>
        <a class="mdl-navigation__link" (click)="goToCadiz()">Valencia</a>
        <a class="mdl-navigation__link" href="">Cádiz</a>
        <a class="mdl-navigation__link black-text" href="">ABOUT</a>
      </nav>
    </div>
    <main class="mdl-layout__content">
      <div class="page-content"><app-content *ngIf="cityName" [cityName]="this.cityName"></app-content></div>
    </main>
  </div>
</div>

This is my cities-nav.component.ts:

import { Component, OnInit, NgZone } from "@angular/core";
import { Location } from "@angular/common";
import { ActivatedRoute } from "@angular/router";
import { Router } from "@angular/router";

@Component({
  selector: "app-cities-nav",
  templateUrl: "./cities-nav.component.html",
  styleUrls: ["./cities-nav.component.scss"]
})
export class CitiesNavComponent implements OnInit {
  cityName: string;

  constructor(
    private location: Location,
    private route: ActivatedRoute,
    private router: Router,
    private ngZone: NgZone
  ) {}

  ngOnInit() {
    console.log("Cities nav component OnInit executed");
    this.cityName = this.route.snapshot.paramMap.get("name");
  }
  goToCadiz() {
    this.ngZone.run(() => {
      this.router.navigateByUrl('/cities/Cadiz');
    });
  }
}

View the first screenshot of tracing View the second screenshot of tracing

Answer №1

Finally discovered the root of the issue after much troubleshooting. It turns out there were actually two distinct problems at play.

To start, I needed to make a modification in the cities-nav.component file:

this.cityName = this.route.snapshot.paramMap.get("name");

Needed to change this to:

this.activeRoute.params.subscribe(routeParams => {
  this.cityName = routeParams.name;
  })

Since I was consistently on the 'cities/:name' path, even when transitioning between cities, it wasn't pulling the new name from the input. Subscribing to the params resolves this issue by providing the updated param each time the variable changes within the same path.

The other issue stemmed from the app-content section, where I was invoking the cityService to retrieve a city by name within the onInit method. This problem mirrored the previous one, as it only fetched the city information once, failing to update when the city input name changed. The solution involved implementing the ngOnChanges method like so:

ngOnChanges(changes: SimpleChanges): void {
//Add '${implements OnChanges}' to the class.
this.getCityByName(this.cityName);
}

By implementing this method, the component now fetches the new city information and updates every time the 'cityName' input changes.

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 is the best way to implement dynamic comment display similar to Stack Overflow using Asp.net and Jquery?

I have created a small web application using Asp.net and C#. Currently, I am able to retrieve comments by refreshing the entire page. However, I would like to achieve this functionality without having to do a full refresh. For instance Let's say the ...

Trying to add a single value to a specific index in a JavaScript array, but it is mistakenly assigning multiple values at once

Currently tackling a matrix algorithm with an early roadblock. The array at hand is: [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ] The goal is to convert it into this: [ [ 0, 0, 0 ], [ 0, 9, 0 ], [ 0, 0, 0 ] ] My plan was to alter the middle value like so ...

An issue occurred when attempting to create a collapsible/expandable button within an Angular Material Nested Tree

I am currently working on an Angular Material Nested tree and I'm facing an issue while trying to implement a button for expanding/collapsing. The error message I encounter is: ERROR TypeError: Cannot read property 'reduce' of undefined ...

Can the AJAX URL be loaded onto a new page?

https://i.stack.imgur.com/5l63v.pngPardon the poorly phrased question, but I need some guidance on a specific requirement regarding opening a URL in a new page. Currently, I have designed an AJAX URL and I'm wondering if it's possible to open thi ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

When you click on the mat-tab label, it will act as a link and directly open the

I am facing an issue where I have 4 mat-tabs and I want to add one more tab. This additional tab will act as a label that, when clicked, opens a provided link. I have tried the following code but it is not working: <mat-tab label="Statistik ...

The method element.isDisplayed() is indicating a false value even though the element is visibly present on the screen

element.isDisplayed() is returning false even though the element is visible on the screen, causing issues with clicking on it. I attempted to use the code below, but without success. Actions cursor = new Actions(driver); cursor.moveTo ...

Exploring the capabilities of Express.JS for integrating with an external API

const express = require('express'); const app = express(); const path = require('path'); const api = require('./api'); app.get('/', function(req, res){ res.sendFile(path.join(__dirname + '/index.html')); ...

Getting to the values within a JSON object that contains multiple arrays

Is there a way to retrieve array data from the json object data? const [data, setData] = useState([]) const getData = () => { axiosInstance .get(url + slug) .then(result => setData(result.data)) } useEffect(() = ...

The SyntaxError is triggered by the React-Native FlatList component

As a newcomer to React Native, I am facing an issue with refreshing the component to load city names stored in async storage. The error occurs when I utilize the FlatList component for the first time. The specific error message I encountered is: SyntaxE ...

How to replace/redirect the import statement in TypeScript from { X } to 'Y'

My situation involves an external library known as Y, which was installed using npm and loaded from the node_modules directory. This library is hosted on GitHub and currently being utilized in my project in the following manner: import { X } from 'Y& ...

Exploring Appsetting Configuration in AppModule of Angular 8

I'm looking to update my configuration in the appsettings file by replacing a hardcoded string with a reference to the appsetting. Currently, I have this hardcoded value in appmodule.ts: AgmCoreModule.forRoot({ apiKey: 'testtesttest', li ...

Utilizing JavaScript within the realm of React

Hello everyone, new to React here! I've been working on integrating a Google map into my page. While exploring the samples on the Google Maps platform, I came across this interesting link: https://developers.google.com/maps/documentation/javascript/ex ...

I obtained the binary tree output in the form of an object. How can I extract the values from this object and store them in an array to continue working on

Issue Statement In this scenario, you have been presented with a tree consisting of N nodes that are rooted at 1. Each node in the tree is associated with a special number, Se. Moreover, each node possesses a certain Power, which is determined by the count ...

Determining whether a path is absolute or relative: A step-by-step guide

Is there a universal function in node.js that can determine if a given path is absolute or relative? Unlike Windows, which starts with 'C:' or '\', UNIX paths begin with '/'. ...

Having trouble with executing functions on an express js Route?

I'm currently exploring Node and Express, and I'm encountering an issue when trying to pass a function instead of plain text on my route. It seems that the documentation only mentions using res.send() method with text. Even when attempting to use ...

The jQuery .click() function is not triggering when clicked

$("#backButton-1").click(function() { $("#form-2").empty(); $("#form-1").show(); }); I am experiencing trouble with this code snippet. The form-1 element is hidden, and the backButton-1 is created after the end of for ...

Step by step guide to creating individual counter sections

I have set up a counter section where the numbers go from 0 to a specific value. However, currently all three counters start counting simultaneously. Is there a way for the first counter to count up first, then once it's done, move on to the second c ...

What steps can be taken to extend the duration that the HTML necessary validation message is displayed?

Is it possible to extend the duration in which the HTML required validation message is displayed? Currently, it seems to appear for too short a time. https://i.sstatic.net/DdqH6.jpg ...