Alter the navigation but keep the URL intact without modifying the view

I have an Angular project that includes a login component.

The login component is located in the directory app/main/login.

I am trying to navigate to the login component from app.component.html using a button.

Below is the code snippet from my app-routing.module:

    import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './main/login/login.component';

const routes: Routes = [
  { path: 'main', children: [{ path: 'login', component: LoginComponent }] },
];

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

This is how I am attempting to use the route:

<button mat-raised-button class="btn-default" [routerLink]="['/main/login']">Log in</button>

Here is the content of app.module.ts:

    import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {MatButtonModule} from '@angular/material/button';
import {MainModule} from  './main/main.module'
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MatButtonModule,
    MainModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And here is the code from main.module.ts:

 import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { LoginComponent } from './login/login.component';

@NgModule({
  declarations: [LoginComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [],
})
export class MainModule {}

When clicking the button, the URL changes to http://localhost:4200/main/login, but the view does not change. How can I resolve this issue?

Answer №1

After reviewing your code, it appears that you are attempting to implement lazy loading for a component. To achieve this in the AppRoutingComponent.ts file, make the following adjustment:

const routes: Routes = [
  { path: 'main', loadChildren: '(path to main module)/main.module#MainModule' },
];

In simple terms, this configuration instructs the parent routing module to load the main module when the main path is accessed.

Next, within the Main.module, set up child routes like so:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
    { path: 'login', component: LoginComponent }
];

@NgModule({
  declarations: [LoginComponent],
  imports: [
             BrowserModule, 
             RouterModule.forChild(routes) // Instead of using forRoot, register routes for the child module with the forChild function
           ],
  providers: [],
  bootstrap: [],
})
export class MainModule {}

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

Is Express capable of serving static files from a hidden folder with dot file?

I have set up my app to serve a static folder in the following way: app.use('/static', serveStatic(__dirname + '/view/my/static/folder')); Now, I am wondering how to configure the server to serve a hidden folder. For example, if I hav ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

Terser is causing ng build --prod to fail

When I run ng build --prod on my Angular 7 application (which includes a C# app on the BE), I encounter the following error: ERROR in scripts.db02b1660e4ae815041b.js from Terser Unexpected token: keyword (var) [scripts.db02b1660e4ae815041b.js:5,8] It see ...

Whenever I use Vue JS, I notice that it displays [Object object] on console.log and returns Undefined when

Currently, I'm developing Vue.JS code to showcase data fetched by PHP from a server. The PHP sends a JSON object to the Vue for display. Below is my existing code snippet: axiosPost(); } function axiosPost() { axios.post( './Conver ...

Bypass Security Check in Firefox

I am facing issues while trying to automate selenium on a website owned by a third party. When an authentication prompt like this appears in Firefox, Selenium fails: You can see a similar situation when clicking the Display Image button here Is there a ...

Facing a challenge in configuring MongoDB automatic data expiration based on specific time zones

I am currently facing an issue with clearing data in MongoDB at the start of each day. For example, on July 15, 2020 at 00:00:00, data is deleted from the database based on a specific time. I am having trouble properly assigning the expiresAt attribute in ...

What are the steps to leverage npm installed packages in my .js files?

I'm new to web development and I'm trying to incorporate node packages into my workflow. Specifically, I'm attempting to test out the axios ajax library. It seemed like this would be a simple task, but it's proving to be quite challeng ...

"Utilizing Material-UI in React to create a textfield input with number validation

I am currently working on an input field that should only accept values within a specified range of min and max. However, I have encountered an issue where manually entering a number bypasses this control mechanism. Is there a way to prevent this from happ ...

Creating a diverse layout by dynamically adding divs without achieving uniformity in the grid

I'm working on dynamically generating a grid of divs with a specific size using the code below: function createGrid(gridSize) { var container = document.getElementById('container'); for (var i = 0; i < gridSize; i++) { va ...

Generating TypeScript declarations for legacy CommonJS dependencies with the correct "module" setting

One of my challenges involves creating type declarations for outdated dependencies that produce CJS modules and lack typings. An example is the aabb-3d module (although this issue isn't specific to that particular module). To generate the declaration ...

recursive algorithm utilizing an array as an argument

Currently, I am in the process of developing a function that extracts chest exercises from an array titled "chest". This particular function is required to randomly select multiple exercises, achieved by utilizing a random pointer. In order to avoid selec ...

Promise not being properly returned by io.emit

io.emit('runPython', FutureValue().then(function(value) { console.log(value); //returns 15692 return value; // socket sends: 42["runPython",{}] })); Despite seeing the value 15692 in the console, I am encountering an issue where the promise ...

Unlocking the power of localhost on your mobile device

Currently, I am working on a web application that utilizes Laravel for APIs and React for the frontend. My goal is to test this application on a mobile device. While testing React in isolation works fine, I am encountering issues with backend data such a ...

Steps to hide a div after it has been displayed once during a user's session

After a successful login, I have a div that displays a success message and then hides after 4 seconds using the following JavaScript code: document.getElementById('success').style.display = 'none'; }, 4000); While this functionality wo ...

Setting up TailwindCSS in Nuxt3: A step-by-step guide

Looking to customize the default font Proxima Nova from TailwindCSS in my Nuxt3 project but navigating the file structure is a bit tricky for me. I've gone ahead and installed the tailwindcss module: npm i -D @nuxtjs/tailwindcss and added the module ...

Spinning divs using JavaScript when the mouse hovers over them, and then returning them to their original position when the mouse moves

I am looking to create a functionality where a div rotates when the mouse enters it and returns to its original position when the mouse leaves. Everything works fine when interacting with one div, but as soon as I try hovering over other divs, it starts gl ...

Launching a Nuxt.js Cloud Function

Is there a possibility to deploy a cloud function that allows for server-side rendering with Nuxt on Firebase? The issue lies in the fact that the Node version used on Firebase is 6.11.1 while the minimum required Node version for Nuxt versions 1 and above ...

Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone g ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Connecting Angular forms to retrieve form data using email

Hello, I am new to Angular and haven't had experience hosting a website before. I have created a contact form on my website and would like the form inputs to be sent to my email address whenever someone submits the form. Can anyone guide me on how to ...