在md-accordion中创建动态md-expansion-panel组件

时间:2017-08-07 07:12:30

标签: angular angular-material2

我在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答案很有用。请帮我。提前谢谢。

1 个答案:

答案 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