导航到角度4

时间:2018-07-19 09:34:13

标签: angular angular4-router

我创建了一个名为登录页面的新模块,我想从app.component.html导航到该模块

然后通过app.component.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>

app.modules.ts文件如下所示

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

它的导航很好,但是它的内容(login-page.component.html)显示在同一页面(app.component.html)中。我希望它显示在单独的页面中。如何实现呢?

2 个答案:

答案 0 :(得分:2)

AppComponent 是主要组件,其他组件也呈现在其中。 因此,您要做的是从Appcomponent中删除内容,然后通过另一条路线将这些内容添加到组件中。 然后默认情况下调用该路由,并在需要时导航至该位置的登录路由。

然后您的代码将如下所示,

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>

也请阅读DOCS

答案 1 :(得分:2)

这样的设置很容易

  1. <router-outlet></router-outlet>放入应用程序的内部 组件要在其上重新路由的位置
  2. 您的路线

    { path: 'login-page', component: LoginPageComponent },
    { path: 'signup-form', component: SignupFormComponent } , 
    { path :'',redirectTo:'login-page',pathMatch:'full'} // defualt route
    

希望它能起作用。

相关问题