【问题标题】:Angular 4 - completely route to new componentAngular 4 - 完全路由到新组件
【发布时间】:2026-02-17 23:25:01
【问题描述】:

我正在使用routerLink 从当前的component 导航到新的component

<div class="form-list-container">
<h3>Contact Form</h3>
<button md-raised-button routerLink="/add-form" 
routerLinkActive="active">Add New</button>

<all-forms></all-forms>

<router-outlet></router-outlet>
</div>

单击Add New 按钮后,它会将/add-form 路由器组件视图呈现给

&lt;router-outlet&gt;&lt;/router-outlet&gt;

以及所有其他 HTML 元素。

编辑

对于路由,我有以下代码 -

const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full'},
{ path: 'home',   component: AppComponent },
{ path: 'add-form',  component: AddFormViewComponent },
]

当用户点击Add New 按钮时,我希望用户继续AddFormViewComponent 视图,而不是在当前component 中添加AddFormViewComponent 视图。

【问题讨论】:

  • 然后把所有其他的 HTML 放到当前组件的视图中。

标签: angular


【解决方案1】:

如果我很好理解你想要做什么,你需要创建两条路线。

我用来创建路由模块。 app-routing.module.ts :

const routes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full'},
    { path: 'home',   component: Component1 },
    { path: 'add-form',   component: Component2 }
]

@NgModule({
    imports: [ RouterModule.forRoot(routes)],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

在app.module.ts中,添加路由模块导入:

imports: [
    ...,
    AppRoutingModule ]

app.component.html 只能包含一行:

<router-outlet></router-outlet>

component1.component.html:

<div class="form-list-container">
<h3>Contact Form</h3>
<button md-raised-button routerLink="/add-form" 
routerLinkActive="active">Add New</button>

<all-forms></all-forms>

</div>

component2.component.html 不应更改。

【讨论】:

    【解决方案2】:

    应该是这样的

    <div class="form-list-container">
     <h3>Contact Form</h3>
     <button md-raised-button routerLink="/add-form" 
      routerLinkActive="active">Add New</button>
    
     <all-forms></all-forms>
    </div>
    <router-outlet></router-outlet>
    

    【讨论】: