在 md-accordion 中创建动态 md-expansion-panel 组件
Creating dynamic md-expansion-panel component inside md-accordion
我正在 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,
})
根据angular显然会在html结构中寻找<md-accordion><app-create-pie-element><md-expansion-panel>....
。如何实现<md-accordion><md-expansion-panel>
这个结构,
答案在通过循环创建组件时很有帮助。请帮我。提前致谢。
一个可能的解决方案是让 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);
我正在 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,
})
根据angular显然会在html结构中寻找<md-accordion><app-create-pie-element><md-expansion-panel>....
。如何实现<md-accordion><md-expansion-panel>
这个结构,
一个可能的解决方案是让 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);