经过一周的研究,我能够创建一个动态组件。我想出了这个:
import { Component, Input, ComponentRef,ViewChild,ViewContainerRef, ComponentFactoryResolver} from '@angular/core';
import { AfterViewInit,OnInit,OnDestroy} from '@angular/core';
import { OnChanges,SimpleChange,ComponentFactory} from '@angular/core';
import { TestModule } from './test.module';
import { TestComponent } from './test.component';
@Component({
selector: 'dynamic-detail',
template: `<div> <div #dynamicContentPlaceHolder></div> </div> `,
})
export class DynamicDetail implements AfterViewInit, OnChanges, OnDestroy, OnInit {
@ViewChild('dynamicContentPlaceHolder', {
read: ViewContainerRef
})
protected dynamicComponentTarget: ViewContainerRef;
// this will be reference to dynamic content - to be able to destroy it
protected componentRef: ComponentRef < IHaveDynamicData > ;
// until ngAfterViewInit, we cannot start (firstly) to process dynamic stuff
protected wasViewInitialized = false;
// wee need Dynamic component builder
constructor(
protected typeBuilder: DynamicTypeBuilder,
private componentFactoryResolver: ComponentFactoryResolver
) {}
/** Get a Factory and create a component */
protected refreshContent() {
if (this.componentRef) {
this.componentRef.destroy();
}
const childComponent =this.componentFactoryResolver.resolveComponentFactory(TestComponent);
this.componentRef = this.dynamicComponentTarget.createComponent(childComponent);
...
}
...
}
我的测试组件
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'dynamic-component',
template: 'i am dynamic',
})
export class TestComponent implements OnInit {
@Input() public entity: any;
constructor(){}
public ngOnInit(): void {}
}
和模块
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { TestComponent } from './test.component';
@NgModule({
imports: [ CommonModule, BrowserModule ],
declarations: [ TestComponent ],
entryComponents: [ TestComponent ],
providers: [ ]
})
export class TestModule { }
工作正常。我的问题是,我如何将动态模板传递给组件?
例如在TestComponent
中@Component({
selector: 'dynamic-component',
template: $dynamicTemplateVariable,
})
并在我的主要组件中
this.template = "<div>i am generated form another source</div>"
this.componentRef = this.dynamicComponentTarget.createComponent(childComponent, this.template);
模板可以从任何来源,也可以从api获得。