使用Angular2中的单一应用程序在同一页面中的多个组件

时间:2016-09-04 05:03:54

标签: angular angular2-routing angular2-template angular2-directives

如何在Angular2中将html的一部分从子级呈现为父级。 我们的想法是制作一个主要布局,并根据要求由儿童覆盖(填充)此布局的各个部分。 我试过了。路线,但我无法使它工作。 PS:我不希望这部分拥有它自己的路线,因为它只是页面的一部分。 最新的Angular2请!

例如

<div class="layout">
    <div class="page-header">
        //Another router outlet here (How to render also this part for each child seperate)
        //Some children will have custom page header
    </div>
    <div class="content">
        //content from child is rendered here
        <router-outlet></router-outlet>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

由于您不想要单个模板的特定路径,因此您可以按照以下方式实现此目的。

假设在加载时你是引导appComponent。

app.component.html

<div class="layout">
    <div class="page-header">
        //Another router outlet here (How to render also this part for each child seperate)
        //Some children will have custom page header
        <router-outlet name='child1'></router-outlet>
    </div>
    <div class="content">
        //content from child is rendered here
        <router-outlet name='child2'></router-outlet>
    </div>
</div>

将以下内容添加到路由器中。

{
    path: 'home',  // you can keep it empty if you do not want /home
    component: 'appComponent',
    children: [
        {
            path: '',
            component: childOneComponent,
            outlet: 'child1'
        },
        {
            path: '',
            component: childTwoComponent,
            outlet: 'child2'
        }
    ]
}

现在当加载/ home时,appComponent将使用已分配的模板加载,然后角度路由器将检查路由并根据名称加载指定路由器出口中的子组件。