Go to a specific component located in a different module within Angular

I have a default app.component that contains a button. When this button is clicked, I want to navigate to the login.component.

Below is a snippet from my app.module.ts file:

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

        import { AppRoutingModule } from './app-routing/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, MatButtonModule, MainModule, AppRoutingModule],
          providers: [],
          bootstrap: [AppComponent],
        })
        export class AppModule {}
    

And here is a snippet from my app-routing.module.ts file:

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 {}
    

In order to achieve this navigation, I used the following code:

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

To see the code in action, you can visit the following Stackblitz link.

My issue is that although the URL changes to localhost:4200/main/login, the view does not update accordingly. How can I resolve this?

Answer №1

If you're encountering a CSS problem, the issue might lie in the layout of the elements. It seems like the 'split left' and 'split right' sections are not providing enough space for the login component. One solution could be to treat your main page (main-page) as a separate component, containing the login and sign up buttons, while using the 'split right' section solely for the router outlet.

Take a look at the code snippets below:

app.component.html

<div class="split left">
  <div class="centered">
    <h1>Learn what you want.</h1>
    <h1>Teach what you love.</h1>
  </div>
</div>

<div class="split right">
  <router-outlet></router-outlet>
</div>

main-page.component.html

<div class="centered">
    <div>
      <button mat-raised-button class="btn-default" [routerLink]="['/main/login']">Log in</button>
    </div>
    <div style="margin-top: 20px">
      <button mat-raised-button class="btn-default-transparent">Sign up</button>
    </div>
  </div>

Answer №2

Check out the updated version with bug fixes here: Stackblitz

The issue you were facing was that it was loading behind the app.component.html template. To resolve this, I created a main module for the LoginComponent and implemented Lazy Loading in my demo. It's recommended to have the main app component, app-component, only contain

<router-outlet></router-outlet>
for loading content from other components.

Answer №3

The issue did not reside in CSS

It turned out that all components needed to be individual, with the

<router-outlet></router-outlet>
only in the app.component.ts file.

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

Navigating through template files in Angular 2 components

Currently, I am working on developing a top-level component that requires an input of type @Input(): Object. This object needs to contain an array of components, which will be iterated through using *ngFor, and the templates of these components must be p ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Caution: Discrepancy found in Prop className between server and client rendering in a React SSR application

Currently, I am working on integrating a collapsible sidebar into my React application that relies on a value stored in the local storage. The intended behavior is for the sidebar to have the className of "inline" if the value is true, and "hidden" if the ...

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

Managing events like onClick for custom components in Next.js and React: A Beginner's Guide

Utilizing tailwindCSS for styling and writing code in Typescript with Next.JS. A reusable "Button" component has been created to be used across the platform. When the button is pressed, I aim to update its UI in a specific way. For instance, if there&apos ...

I'm curious as to why my array is only being filled within the subscription function

When I call the GetAllMainStore() function, data is successfully retrieved from the API and the console indicates that "this.MainStoreArray" contains data. The problem arises when I attempt to access "this.MainStoreArray" outside of the GetAllMainStore() ...

Getting News API and showcasing the information in Vuetify.js card components: A step-by-step guide

I'm trying to develop a news website by utilizing the News API for news data. I obtained an API Key from the official News API website, but my code is encountering some issues. The error message reads: TypeError: response.data.map is not a function ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

What is the best way to represent a directory structure in JSON using a C# data type?

My directory structure is as follows: v1 file1.txt file2.txt common common.txt I need to create a C# function that can traverse this directory structure and generate JSON output. The expected JSON format is like this: { "v1&qu ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

Running an HTTP request conditionally within combineLatest

I'm working on a combineLatest function that makes 2 http requests, but I only want the second request to be made if a specific condition is satisfied. combineLatest([ this.leadsService.fetchALLLeadsActivityChart(this.clientId, this.getParams(option ...

The animation of a disappearing div with CSS is not stopping when hovering over it

Hello, I've been working on a snackbar feature that appears and disappears on a set timer but also needs to pause when hovered over. Unfortunately, the current setup with setTimeout and useState is causing issues with this functionality. I have looke ...

Guidelines for validating email input using jQuery

Although I am not utilizing the form tag, you can still achieve form functionality using jQuery Ajax. <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password ...

Showcase information from APIs using Vue.js

I am facing an issue where I am able to fetch data correctly from the API, but I am unable to display it. When I manually input items, they are displayed, but the items fetched from the API remain invisible. I even attempted to move the API call directly i ...

Inputting data types as arguments into a personalized hook

I am currently developing a Next.js application and have created a custom hook called useAxios. I am looking to implement a type assertion similar to what can be done with useState. For example: const [foo, setFoo] = useState<string>(''); ...

Is it possible to deceive Array.isArray?

Although I have a good understanding of prototypes, I encountered some confusion when I attempted the following: var obj = {}; Object.setPrototypeOf(obj, Array.prototype); console.log(Array.isArray(obj)); // false? What's even more perplexing: var ar ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...

JavaScript: Display all global variables on Internet Explorer

Is there a way to retrieve the instance name of my class without passing it as a parameter? I have tried looping through all global objects and comparing them with the this pointer. This method works in Chrome and Firefox, but not in Internet Explo ...