我已经看到了<ng-content>在其他嵌套组件中使用的工作示例(例如http://plnkr.co/edit/Hn393B9fJN6zgfaz54tn),但我还没有设法在根Angular2组件中运行它:
HTML模板:
<html>
<body>
<app>
<h1>Hello, World!</h1>
</app>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
打字稿中的Angular2组件:
import {Component, View, bootstrap} from 'angular2/angular2';
@Component({
selector: 'app'
})
@View({
template: 'Header: <ng-content></ng-content>',
})
export class App {
}
bootstrap(App);
Run Code Online (Sandbox Code Playgroud)
我希望这会产生:
<app>
Header: <h1>Hello, World!</h1>
</app>
Run Code Online (Sandbox Code Playgroud)
但它没有,内容<app>被忽略了.请参阅Plunker http://plnkr.co/edit/dJlA4SQpy8pnrdyDiy9u上的演示.
我想也许这会再次出现一些Angular2哲学或其他东西,所以它甚至不支持,但我的用例与我认为的第一个工作演示非常相似.
Jes*_*ood 25
运行示例时,您是否注意到Hello World!在加载过程中如何显示?
基本上,<app>和之间的html </app>用于在Angular启动时显示某些内容.
另外,从来源:
通常,应用程序在现有浏览器DOM中引导
index.html.与Angular 1不同,Angular 2不会编译/处理绑定index.html.这主要是出于安全原因以及Angular 2中的体系结构更改.这意味着index.html可以使用服务器端技术(如绑定)安全地进行处理.因此,绑定可以使用双卷曲{{ syntax }}而不会发生Angular 2组件双卷曲的冲突{{ syntax }}.
重要的是Angular 2 does not compile/process bindings in index.html.因此,为了做你想做的事,你将不得不转移ng-content到子组件.
And*_*ang 12
如果您打算提供文本内容,则可能会发生这种情况.如果你想要Angular组件,可以使用正确的HTML元素(noscript).有人可能会说,有点hacky.诀窍是使用<noscript>元素.
HTML模板:
<noscript id="appContent">
<h1>Hello, World!</h1>
<a [routerLink]="['Home']">Home</a>
</noscript>
<script>
var mainTemplate = document.getElementById('appContent');
window.mainTemplate = mainTemplate.innerText;
</script>
Run Code Online (Sandbox Code Playgroud)
根组件:
import {Component, bootstrap} from 'angular2/angular2';
@Component({
selector: 'app',
template: 'Header: ' + window.mainTemplate ,
})
export class App {
}
bootstrap(App);
Run Code Online (Sandbox Code Playgroud)
确保Angular 2代码位于模板定义之后.
仅适用于使用<template>标签的情况:自最近以来(http://angularjs.blogspot.com.br/2016/02/angular-2-templates-will-it-parse.html),Angular 2带来了自己的标签解析器,模板区分大小写.在浏览器环境中不是HTML的情况.这意味着浏览器可能无法将此案例保留在此模板上的属性和元素中.
更新:我<template>在原始解决方案中有一个元素.A <noscript>更好,因为不应该是任何情况转换.