【问题标题】:Angular2 dynamic templatingAngular2动态模板
【发布时间】:2016-12-07 08:39:33
【问题描述】:

如何在 angular2 中使用嵌套模板。所以基本上我有一个基本组件,它是子组件

- entry.component.ts
- entry.component.html
- navigation
-- sidenav.ts
-- sidenav.html
-route1
--route1.ts
--route1.html

entry.component.html 应该是一个骨架,内容应该在路由变化时动态生成。

有可能实现吗?

【问题讨论】:

  • 你的意思是你要使用模板然后在模板中显示组件?
  • 是的,这就是想法。不要重复使用多次模板部分
  • 您的需求看起来像路由的基本行为,查看文档,router-outlet 是关键。 angular.io/docs/ts/latest/guide/router.html

标签: templates angular inheritance


【解决方案1】:

使用带有子路由的模板。

我在publicsecure 中分开我的,通过布局路由所有内容,然后加载选择任何布局的路由。

确保导出子路由并在布局路由中调用正确的路由。还要确保在每个子路由文件中使用redirectTo

app.routing.ts

    const APP_ROUTES: Routes = [
        { path: '', redirectTo: '/home', pathMatch: 'full', },
        { path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
        { path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
    ];

然后我有一个布局文件夹

布局

layouts/public/public.components.ts
layouts/public/public.components.html
layouts/secure/secure.components.ts
layouts/secure/secure.components.html

子路线 /public/piublic.routes.ts

 export const PUBLIC_ROUTES: Routes = [
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'p404', component: p404Component },
        { path: 'e500', component: e500Component },
        { path: 'login', component: LoginComponent },
        { path: 'register', component: RegisterComponent },
        { path: 'home', component: HomeComponent }
    ];

/secure/secure.routes.ts

export const SECURE_ROUTES: Routes = [
    { path: '', redirectTo: 'overview', pathMatch: 'full' },
    { path: 'items', component: ItemsComponent },
    { path: 'overview', component: OverviewComponent },
    { path: 'profile', component: ProfileComponent },


 { path: 'reports', component: ReportsComponent }
];

创建要加载到模板中的组件

import { Component, OnInit } from '@angular/core';

@Component({
  templateUrl: './benefits.component.html',
})
export class BenefitsComponent {

  constructor() { }

}

创建它的html模板,

/public/benefits.component.html'

现在它是公共路线的一部分。当有人去公共路线时,它将被加载到智利路线中。所以在你的里面 /public/public.routes.ts 文件,您可以为要创建的每条新路线添加它,以加载新的 html 页面。

【讨论】:

    猜你喜欢
    • 2016-03-29
    • 2017-01-12
    • 2016-03-31
    • 2017-04-08
    • 2017-02-07
    • 2017-08-25
    • 2016-10-05
    • 2017-08-27
    • 2019-03-13
    相关资源
    最近更新 更多