Angular2组件——从索引页渲染html
Angular2 component - render html from the index page
是否有可能在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,我想渲染它。
您可以使用ngTemplateOutlet
投影嵌入视图。在<template>
的<app-nav>
标签中包装你的内容。然后在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中创建模板出口和相对模板上下文
<template [ngOutletContext]="{ title: title }" [ngTemplateOutlet]="defaultTemplate"></template>
....other component content....
然后在组件使用的地方:
<app-nav>
<template #defaultTemplate let-title="title">
nav works! {{ title }}
</template>
</app-nav>
乌利希期刊指南:
这里有一个示例
在app/some.component.ts
中有app/app.component.ts
template
的ngTemplateOutlet
投影
乌利希期刊指南:
好的,有一种方法可以将index.html中的初始内容获取到组件中。您可以使用APP_INITIALIZER
函数,该函数将在应用程序初始化时执行。
在这里
- 参见
app/root-template.initializer.ts
在
获得的。app/app.component.ts
中,我只是将相关属性替换为初始内容。这是一个有点粗糙的方式,应该通过替换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的信息
@Yaroslav,扩展您的解决方案:
-
看起来像一个透传(在Angular 1中),所以在Angular 2中,你可以在内部组件中使用ng-content。
<div class="my-component"> <ng-content></ng-content> </div>
-
要在外部跨包标记上进行插值,请给元素一个id并将其作为插值内容的前缀。
<my-component #comp> This is my transcluded content! ++{{comp.title}}++ </my-component>
-
不要尝试从index.html中跳转,它不是一个有角度的组件,所以它似乎不能作为外部组件工作。如果你使用app.component作为外部组件,另一个my.component作为内部组件,它就可以工作了。
这是你的叉子与变化。plnkr
作为参考,我使用了Todd Motto关于角2透光的优秀文章:参考这里。
angular指南只是模糊地引用了ng-content(带有404的链接),所以我想知道它是否正在消失。可以被ngComponentOutlet ref here
- 在索引.html和应用.js [node.js] 之间共享变量
- 限制对HTML/CSS/IMG或根索引文件夹的访问
- D3选择html——传递函数时,索引从1开始,而不是从0开始
- Disqus的计数.js脚本在索引中无法正常运行.html与react.js网站
- 如何设置元素的z索引?JQuery、Javascript、CSS、HTML
- 使url匹配'/''/索引'和'/index.html'到单一状态
- 将HTML输入到包含的索引页中
- html元素是'由于父级的z索引为负,t注册js点击
- 将JSON从索引操作服务到公用文件夹中的index.html
- 节点.js socket.io 网络服务器提供索引.html以外的其他文件
- 为什么 “/” 在节点.js中没有提供索引.html
- 同时使用索引.html和索引.php时,从 URL 中隐藏索引.php
- 如何删除索引中加载的脚本文件中的重复项.html和业力
- Jquery 复制了具有特定索引的 html 类,无法识别点击事件
- 如何观察聚合物元素属性值从索引.html的变化
- 如何将此功能实现到我的索引.html
- 如何打开另一个文件索引.html,具体取决于屏幕的宽度
- 当 Angular 索引页面加载到 DOM [Angular 模板到静态 HTML] 中时,我可以拍摄它的纯 HTML
- 第三方(随机网站访问者)是否有可能通过 php 表单更新.html索引文件中的某些.js代码
- 如何在 html 索引中引用两个使用 jquery 的 HTML 文件