<ng-content> 的组件

Component with <ng-content>

我看过 <ng-content> 在其他嵌套组件(如 here)中使用时的工作示例,但我还没有设法 运行 它在根 Angular2 个分量:

HTML 模板:

<html>
    <body>
        <app>
            <h1>Hello, World!</h1>
        </app>
    </body> 
</html>

Angular TypeScript 中的 2 个组件:

import {Component, View, bootstrap} from 'angular2/angular2';

@Component({
    selector: 'app'
})
@View({
    template: 'Header: <ng-content></ng-content>',
})
export class App {
}

bootstrap(App);

我希望这会产生:

<app>
    Header: <h1>Hello, World!</h1>
</app>

但它没有, <app> 的内容被忽略。请参阅 Plunker.

上的演示

我认为这可能违背了某些 Angular 2 理念或其他东西,因此它甚至不受支持,但我的用例与我认为的第一个 working demo 非常相似。

当您 运行 您的示例时,您是否注意到 Hello World! 在加载过程中的显示方式?

基本上,<app></app> 之间的 HTML 用于在 Angular 启动时显示一些东西。

此外,来自 source

An application is bootstrapped inside an existing browser DOM, typically index.html. Unlike Angular 1, Angular 2 does not compile/process bindings in index.html. This is mainly for security reasons, as well as architectural changes in Angular 2. This means that index.html can safely be processed using server-side technologies such as bindings. Bindings can thus use double-curly {{ syntax }} without collision from Angular 2 component double-curly {{ syntax }}.

重要的部分是 Angular 2 does not compile/process bindings in index.html。因此,为了执行您想要的操作,您必须将 ng-content 移动到子组件。

事实证明这是可能的,如果您打算提供文本内容。如果您想要 Angular 组件,可以使用正确的 HTML 元素(无脚本)。有点 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>

根组件:

import {Component, bootstrap} from 'angular2/angular2';

@Component({
    selector: 'app',
    template: 'Header: ' + window.mainTemplate ,
})
export class App {
}

bootstrap(App);

确保您的 Angular 2 代码位于模板定义之后。

仅在您使用 <template> 标签时适用: 问题是最近 (http://angularjs.blogspot.com.br/2016/02/angular-2-templates-will-it-parse.html) Angular 2 带来了自己的解析器,模板是区分大小写的。在浏览器环境中 HTML 不是这种情况。这意味着浏览器可能不会保留此模板 hack 的属性和元素中的大小写。

更新:我在原始解决方案中有一个 <template> 元素。 <noscript> 更好,因为不应该是任何大小写转换。