Navigate to component in another module (Angular)

Viewed 2070

I have app.component which is creating by default and here is a button. When I click it, I want to go to login.component.

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

Here is my app-routing.module.ts code

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

Here is how I try to do this - <button mat-raised-button class="btn-default" [routerLink]="['/main/login']">Log in</button>

Here is stackblitz url to check code Stackblitz

My problem is, that link changed to localhost:4200/main/login, but view not changed.

How I can solve this?

3 Answers

This is a CSS issue. split left and spit right do not give the login component inside any space. Instead, have your main page (main-page) (the page with the login and sign up button) as its own component, and have split right only having the router outlet.

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>

I created a bug-fixed version here for you: Stackblitz

Your problem was that it loaded but behind the app.component.html template. You created a main module for LoginComponent. When You have more than one module the best practice is to use Lazy Loading which I created for you on my demo. In addition, it's better that app-component, mean main app just have <router-outlet></router-outlet> and content loads from other component.

So the problem was not in CSS

Problem was that I need to have all components to be separate and have <router-outlet></router-outlet> only in app.component.ts file.

Related