整页导航角4

时间:2017-11-19 15:50:09

标签: javascript angular angular-router

我是棱角分明的新手,并开始了解路由和组件。不过我有一个问题:

  • 如何导航到第二个页面(组件)并仅显示该内容,而不仅仅是将组件数据加载到<router-outlet></router-outlet>

First page component

Second page component

当我单击按钮时,我希望整个页面仅显示第二个组件数据。我基本上想知道如何在Angular 4中进行整页导航。

app.module.ts

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


import { AppComponent } from './app.component';
import { ApplyComponent } from './apply/apply.component';
import { RouterModule, Routes } from '@angular/router';


@NgModule({
  declarations: [
    AppComponent,
    ApplyComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
    {
        path: 'apply', component: ApplyComponent
    }
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.componenter.html

<div class="container">
<br><br>
<h1 class="header center orange-text">First page</h1>
<div class="row center">

</div>
<div class="row center">

<a
routerLink="/apply"
class="btn waves-effect waves-light"
type="submit" 
name="action">

Second page
</a>

</div>
<br><br>

</div>

<router-outlet></router-outlet>

apply.component(第二页)

<div class="container">
<br><br>
<h1 class="header center orange-text">Second page</h1>
<div class="row center">

</div>
<div class="row center">

<a
routerLink="/"
class="btn waves-effect waves-light"
type="submit" 
name="action">

Back
</a>

</div>
<br><br>

</div>

如果您有任何疑问或需要澄清,请不要犹豫!

事先谢谢! / E

3 个答案:

答案 0 :(得分:0)

在Angular中,您可以将一个组件嵌套到另一个组件中,从而保留父组件,然后在父组件中加载子组件。组件也可以存在而不嵌套到另一个组件中。声明组件标签真正重要的地方。

我们说我们的网站有一个我们想在所有网页上展示的导航栏。首先,一个主要组件(名为app.component)通常具有选择器名称<app-root></app-root>(即如果使用Angular cli创建角项目)将插入index.html,在应用程序启动时加载app.component。现在,由于我们要在所有网页上显示navbar,您可以创建navbar组件并将其选择标记放在app.component.html(这是应用的视图)组件)并放置<router-outlet></router-outlet>。由于app.component是所有其他组件的父级,因此navbar将显示在每个其他组件上。现在,如果我们不希望navbar显示在每个组件上,该怎么办?然后我们反其道而行之,我们不要将<navbar></navbar>放在根目录中。我们将它放在我们希望它显示的组件中,然后每个其他子组件也会显示它。现在,放置在app.component中的每个组件都不会显示navbar

简而言之,如果您只想显示第二个组件数据,请将其设为父组件。希望我回答你的问题。

答案 1 :(得分:0)

您需要/的路线条目,如

所示
RouterModule.forRoot([
{
    path: '', component: DummyComponent, pathMatch: 'full',
    path: 'apply', component: ApplyComponent
}
])

为此你需要一些可能在视图中没有任何内容的组件(如DummyComponent)。它仅用于满足路由器。

具有空路径pathMatch: 'full'且没有子路由的路由需要

''

答案 2 :(得分:0)

您的应用程序根html和父组件将始终显示;您需要的是首页的组件。

> app-component (always displays) //the parent
>      child components
>             Home
>             About
>             Products
>             ...

然后,您的路由器可以路由/显示每个组件(使用父级中的导航栏)