导航到 angular 中的分隔 page/component 4

Navigating to separate page/component in angular 4

我创建了一个名为登录页面的新模块。我想从 app.component.html

导航到该模块

然后link在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)。我希望它显示单独的页面。我怎样才能做到这一点?

AppComponent 是主要组件,其他组件在其中呈现。 因此,您要做的是从 App 组件中删除内容,并将这些内容添加到另一个路由下的组件中。 然后默认调用该路由,并在需要时从那里导航到 login 路由。

那么你的代码将如下所示,

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. <router-outlet></router-outlet>放入app模板中 component this where component realted to route reander
  2. 您的路线

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

希望有用。