父组件如何将多个ng-template传递给子组件?
例如,父组件包含多个ng-template:
在子组件中,它将看起来像这样:
我也尝试将
例如,父组件包含多个ng-template:
<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
没有获取到多个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 solution
我尝试了你的 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>