多个 ng 内容 [英] Multiple ng-content

查看:42
本文介绍了多个 ng 内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 6 中使用多个 ng-content 构建一个自定义组件,但这不起作用,我不知道为什么.

这是我的组件代码:

<ng-content select="#header"></ng-content>

<div class="body-css-class"><ng-content select="#body"></ng-content>

我试图在另一个地方使用这个组件,并在 bodyng-content 的标题 select 中渲染两个不同的 HTML 代码,像这样:

<div #header>这应该在ng-content的标题选择中呈现</div><div #body>这应该在 ng-content 的正文选择中呈现</div>

但组件呈现空白.

你们知道我可能做错了什么吗,或者在同一个组件中呈现两个不同部分的最佳方法是什么?

谢谢!

解决方案

  1. 您可以添加虚拟属性 headerbody,而不是模板引用 (#header, #body).
  2. 并使用带有 select 属性的 ng-content 进行嵌入,例如 select="[header]".

app.comp.html

<div header >这应该在ng-content的header选择中呈现</div><div body >这应该在 ng-content 的 body 选择中呈现</div></app-child>

child.comp.html

<ng-content select="[header]"></ng-content>

<div class="body-css-class"><ng-content select="[body]"></ng-content>

演示

I am trying to build a custom component using multiple ng-content in Angular 6, but this is not working and I have no idea why.

This is my component code:

<div class="header-css-class">
    <ng-content select="#header"></ng-content>
</div>
<div class="body-css-class">
    <ng-content select="#body"></ng-content>
</div>

I am trying to use this component in another place and render two different HTML code inside body and header select of ng-content, something like this:

<div #header>This should be rendered in header selection of ng-content</div>
<div #body>This should be rendered in body selection of ng-content</div>

But the component is rendering blank.

Do you guys know what I could be doing wrong or what is the best way to render two different sections in same component?

Thanks!

解决方案

  1. You could add dummy attributes header and body as opposed to template references (#header, #body).
  2. And transclude using ng-content with select attribute like select="[header]".

app.comp.html

<app-child>
    <div header >This should be rendered in header selection of ng-content</div>
    <div body >This should be rendered in body selection of ng-content</div>
</app-child>

child.comp.html

<div class="header-css-class">
    <ng-content select="[header]"></ng-content>
</div>
<div class="body-css-class">
    <ng-content select="[body]"></ng-content>
</div>

DEMO

这篇关于多个 ng 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆