Angular 2:在组件标记之间渲染内容 [英] Angular 2: Render content between the component tags

查看:82
本文介绍了Angular 2:在组件标记之间渲染内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  import'Component} from'@ angular /核心'; 
@Component({
selector:'app-root',
template:'< div> {{title}}< / div>',
})
导出类AppComponent {
title ='app works!';

$ / code>

使用它就像

 < app-root>忽略的内容< / app-root> 

呈现

 < div>应用程式作品!< / div> 

但是看PrimeNg对话框他们使用这样的组件

 < p-dialog [(visible)] =display> 
< p-header>
此处的标题内容
< / p-header>
Content
< p-footer>
页脚内容
< / p-footer>
< / p-dialog>

作为此处的标题内容,内容和此处的页脚内容不会被忽略,我怎么能做到这一点?

; / ng-content> 添加到组件模板的内容应该被投影的位置:

  @Component ({
selector:'app-root',
template:'< div> {{title}}< / div>
< br>
< ng -content>< / ng-content>',
})
导出类AppComponent {
title ='app works!';
}

预计内容:

 < app-root>这是预计的内容!< / app-root> 

输出结果如下:

 应用程序的作品! 
这是预计的内容!

以下是一篇关于Angular Content Projection(Angular 1 Transclusion)的文章:在Angular 2中使用ng-content 进行包容


When a component is rendered, then content inside is ignored, for example

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: '<div>{{title}}</div>',
})
export class AppComponent {
  title = 'app works!';
}

Using it like

<app-root>Ignored content</app-root>

Render

<div>app works!</div>

But looking PrimeNg dialog they use components like this

<p-dialog [(visible)]="display">
    <p-header>
        Header content here
    </p-header>
    Content
    <p-footer>
        Footer content here
   </p-footer>
</p-dialog>

As "Header content here", "Content" and "Footer content here" are inside components, why are not getting ignored and how can i achive this?

解决方案

Add <ng-content></ng-content> to the component's template where the content should be projected:

@Component({
  selector: 'app-root',
  template: '<div>{{title}}</div>
             <br>
             <ng-content></ng-content>',
})
export class AppComponent {
  title = 'app works!';
}

Content to be projected:

<app-root>This is projected content!</app-root>

The output will be:

app works!
This is projected content!

Here is a great article about Angular Content Projection (Angular 1 Transclusion): Transclusion in Angular 2 with ng-content

这篇关于Angular 2:在组件标记之间渲染内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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