多个 ng 内容 [英] Multiple ng-content
问题描述
我正在尝试在 Angular 6 中使用多个 ng-content
构建一个自定义组件,但这不起作用,我不知道为什么.
这是我的组件代码:
<ng-content select="#header"></ng-content><div class="body-css-class"><ng-content select="#body"></ng-content>
我试图在另一个地方使用这个组件,并在 body
和 ng-content
的标题 select
中渲染两个不同的 HTML 代码,像这样:
<div #header>这应该在ng-content的标题选择中呈现</div><div #body>这应该在 ng-content 的正文选择中呈现</div>
但组件呈现空白.
你们知道我可能做错了什么吗,或者在同一个组件中呈现两个不同部分的最佳方法是什么?
谢谢!
- 您可以添加虚拟属性
header
和body
,而不是模板引用(#header, #body)
. - 并使用带有
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!
- You could add dummy attributes
header
andbody
as opposed to template references(#header, #body)
. - And transclude using
ng-content
withselect
attribute likeselect="[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>
这篇关于多个 ng 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!