【发布时间】:2018-11-28 22:48:17
【问题描述】:
父组件如何将多个ng-templates传递给子组件?
示例 Parent 组件包含多个 ng-templates:
<app-childcomponent>
<ng-template>Item A</ng-template>
<ng-template>Item B</ng-template>
...
</app-childcomponent>
子组件需要从父组件接收ng-templates并放入app-menu:
<app-menu>
<ng-content></ng-content>
</app-menu>
所以它在子组件中看起来像这样:
<app-menu>
<ng-template>Item 1</ng-template> //having trouble sending this to app-menu from parent
<ng-template>Item 2</ng-template> //having trouble sending this to app-menu from parent
<app-menu>
但似乎ng-content 是空的,导致app-menu 没有得到multiple ng-templates。
<app-menu>
//empty
</app-menu>
我尝试了什么?
我尝试通过@input 传递模板。
<app-childcomponent [myTemplate]="myTemplate"></child-component>模板出口。结果:子组件无法获取
ng-templates。
父 html:
<app-childcomponent>
<ng-template>Item 1</ng-template>
<ng-template>Item 2</ng-template>
</app-childcomponent>
父类:
@ContentChild(TemplateRef) templateRef: TemplateRef<any>;
子 html:
<app-menu>
<ng-template [ngTemplateOutlet]="templateRef"></ng-template>
<app-menu>
预计<ng-template [ngTemplateOutlet]="templateRef"></ng-template> 包含
<ng-template>Item 1</ng-template>
<ng-template>Item 2</ng-template>
但它是空的。
回复@Ricardo 解决方案
我试过你的update。它也是空的。
家长:
<app-childcomponent top-left-menu>
<ng-template>Item 1</ng-template>
<ng-template>Item 2</ng-template>
</app-childcomponent>
孩子:
<ng-content select="[top-left-menu]"></ng-content>
我还尝试将ng-template 传递给ng-content,但Print ME! 没有被渲染。它是空的。好像ng-template 不进入ng-content?
家长:
<app-childcomponent [contextMenuSubject]="contextmenuSubject">
<ng-template>Print ME!</ng-template>
</app-childcomponent>
孩子:
<ng-content></ng-content>
【问题讨论】:
-
如果您将其作为输入参数发送,那么您应该使用 NgTemplateOutlet 从模板动态创建组件。你的结果是什么?
-
我将它作为
input参数发送并作为 Input()myTemplate 类型的 ElementRef 接收并尝试使用 {{ myTemplate }} 绘制它。我想这是错误的 X.X -
blog.angular-university.io/… ng-template 和 ngTemplateOutlet 简单解释
标签: javascript html angular typescript