是否可以呈现 app-nav
标签内的 html,而不是在 templateUrl
中提供它?
@Component({
selector: 'app-nav',
// commented out - templateUrl: './nav.component.html',
styleUrls: ['./nav.component.scss']
})
export class NavComponent {
title: string = 'This is my title';
}
html 页面上已有的 html。
<app-nav>
nav works! {{ title }}
</app-nav>
如果我取消对 templateUrl
的注释,那么 app-nav 将被 nav-component.html 页面取代,但我不希望这样。我有动态 html,我想呈现它。
最佳答案
您可以将嵌入式 View 与 ngTemplateOutlet
一起使用投影。将您的内容包装在 <app-nav>
内<template>
中的标签.比在你的NavComponent
找到这个 TemplateRef
与 ContentChild
并将此 templateRef 插入组件的模板传递上下文中,其中包含您的标题变量。像这样:
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.scss']
})
export class NavComponent {
title: string = 'This is my title';
@ContentChild('defaultTemplate') defaultTemplate = null // get templateRef
}
在 nav.component.html 中创建具有相关模板上下文的模板 socket
<template [ngOutletContext]="{ title: title }" [ngTemplateOutlet]="defaultTemplate"></template>
....other component content....
然后代替组件使用:
<app-nav>
<template #defaultTemplate let-title="title">
nav works! {{ title }}
</template>
</app-nav>
更新:
这是一个plunk举例
在app/some.component.ts
有一个ngTemplateOutlet
来自 app/app.component.ts
的投影template
更新:
好的,有一种方法可以将初始内容从 index.html 获取到组件中。您可以使用 APP_INITIALIZER
应用程序初始化时将执行的函数。
这是 plunk
- 参见
app/root-template.initializer.ts
在
app/app.component.ts
我只是用初始内容替换相关属性。这是一种有点 hacky 的方式,应该通过替换ComponentMetadata
中的模板来完成。这是通过 Reflect.getMetadata 获得的:const annotations = Reflect.getMetadata('annotations', NavComponent) const meta = annotations.find(annotation => annotation instanceof ComponentMetadata) meta.template = meta.template.replace( '{{ someVarInTemplate }}', 'initialContentInIndex' )
这样组件模板就会有初始索引内容,并且会被angular解析。 更多关于 Reflect here
关于javascript - Angular2 组件 - 从索引页面呈现 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40324118/