angularangular4-router

Navigating to separate page/component in angular 4


I have created a new module called as login-page. I want navigate to that module from app.component.html

Then link is given through a button in app.component.html is as follows:

<a routerLink="/login-page">
  <button class="ms-Button" id="btn-1">
    <span class="ms-Button-label" id="Sign_up_btn">SignUp</span>
  </button>
</a>

The app.modules.ts file looks like this:

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

import { AppComponent } from './app.component';
import { FlexLayoutModule } from '@angular/flex-layout';
import { LoginPageComponent } from './login-page/login-page.component';
import { RouterModule, Routes } from '@angular/router';
import { SignupFormComponent } from './signup-form/signup- form.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginPageComponent,
    SignupFormComponent
  ],
  imports: [

    BrowserModule,
    FlexLayoutModule,
    RouterModule.forRoot([
      { path: 'login-page', component: LoginPageComponent },
      { path: 'signup-form', component: SignupFormComponent }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

It's navigating fine, but its content(login-page.component.html) is displaying in same page(app.component.html). I want it to in display separate page. How can I achieve this?


Solution

  • AppComponent is the major component and other components are rendered inside it. So what you have to do is remove content from the Appcomponent and add those content to a component under another route. Then by default call that route and when required navigate to login route from there.

    Then your code will be like follows,

    AppModule

       .... 
       RouterModule.forRoot([
        { path: '', pathMatch: 'full', redirectTo: 'initial-page' },
        { path: 'initial-page', component: InitialPageComponent }, // move all your appcomponent code to this component
        { path: 'login-page', component: LoginPageComponent },
        { path: 'signup-form', component: SignupFormComponent }
       ])
       ....
    

    InitialPageComponent.html

    <a [routerLink]="['../login-page']">
            <button class="ms-Button" id="btn-1">
                 <span class="ms-Button-label" id="Sign_up_btn">SignUp</span>
           </button>
    </a>
    

    AppComponent (html)

    <router-outlet></router-outlet>
    

    Also plese read the DOCS