具有< ng-content>的组件 [英] Component with <ng-content>

查看:53
本文介绍了具有< ng-content>的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在其他嵌套组件(例如此处<ng-content>时,我已经看到了工作示例. >),但我没有设法在根Angular2组件中运行它:

I've seen working examples when <ng-content> is beeing used inside other nested components (like here) but I haven't managed to run it inside a root Angular2 component:

HTML模板:

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

TypeScript中的Angular 2组件:

Angular 2 component in TypeScript:

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>的内容将被忽略.请参见柱塞上的演示.

but it doesn't and the content of <app> is ignored. See demo on Plunker.

我认为这可能与Angular 2的某些原理背道而驰,因此甚至不被支持,但是我的用例与第一个

I thought maybe this goes against some Angular 2 philosophy or something so it's not even supported, but my use case is very similar to the first working demo I think.

推荐答案

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

When you run your example, did you notice how Hello World! is displayed during loading?

基本上,<app></app>之间的HTML用于在Angular启动时显示某些内容.

Basically, the HTML between <app> and </app> is used to display something while Angular is booting up.

另外,来自来源:

在现有浏览器DOM(通常为index.html)中引导应用程序.与Angular 1不同,Angular 2在index.html中不编译/处理绑定.这主要是出于安全原因以及Angular 2中的体系结构更改.这意味着index.html可以使用诸如绑定之类的服务器端技术安全地进行处理.因此,绑定可以使用double-curly {{ syntax }},而不会与Angular 2组件double-curly {{ syntax }}发生冲突.

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移至子组件.

The important part being Angular 2 does not compile/process bindings in index.html. So, in order to do what you want, you will have to move ng-content to a child component.

这篇关于具有&lt; ng-content&gt;的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆