我在md-accordion组件中动态创建组件,如下所示
<md-accordion [displayMode]="displayMode" [multi]="multi"
class="md-expansion-demo-width">
<ng-container #piechartsContainer>
</ng-container>
</md-accordion>
@ViewChild("piechartsContainer", {read: ViewContainerRef}) pieChartContainer: ViewContainerRef;
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(CreatePieChartElement);
let componentRef = this.pieChartContainer.createComponent(componentFactory);
这是我插入的组件
@Component({
selector: 'app-create-pie-element',
template:
<md-expansion-panel>
<md-expansion-panel-header>{{title}}</md-expansion-panel-header>
</md-expansion-panel>
,
styles: [],
encapsulation: ViewEncapsulation.None,
})
根据角度显然它在html结构中看起来<md-accordion><app-create-pie-element><md-expansion-panel>....
。如何实现<md-accordion><md-expansion-panel>
这种结构,
This答案很有用。请帮我。提前谢谢。
答案 0 :(得分:0)
一种可能的解决方案可能是ng-template
包裹CreatePieChartElement
模板:
<强> CreatePieChartElement.html 强>
<ng-template #tmpl>
<md-expansion-panel>
<md-expansion-panel-header>{{title}}</md-expansion-panel-header>
<p>Some text</p>
</md-expansion-panel>
</ng-template>
<强> CreatePieChartElement.ts 强>
@ViewChild('tmpl') template: TemplateRef<any>;
然后在父组件
中let componentFactory = this.resolver.resolveComponentFactory(CreatePieChartElement);
let componentRef = componentFactory.create(this.pieChartContainer.injector);
...
this.pieChartContainer.createEmbeddedView(componentRef.instance.template);
<强> Plunker Example 强>