2017-05-25 57 views
0

我想创建一个动态插入模板的标记的ViewRef。这可能基于以下代码示例吗?Angular 2+创建从标记注入到注入到动态模板的ViewRef

template.html

<ng-container *ngTemplateOutlet="dynamic; context: cntx"></ng-container> 
<ng-template #dynamic> 
    <div [innerHTML]="markup"></div> 
</ng-template> 

注射从API调用的标记绑定到DIV的innerHTML属性:

<div> 
    <div id="forViewRef"></div> 
</div> 

component.ts

@ContentChild('#forViewRef', { read: ViewContainerRef }): someHndl; 
private _nativeElem: any; 

constructor(
    private sanitizer: DomSanitizer, 
    private _vcRef: ViewContainerRef, 
    private _resolver: ComponentFactoryResolver) { 
    // to ensure template has been created, #dynamic 
    this._nativeElem = this._vcRef.element.nativeElement; 
} 

// listen to lifecycle hook 
ngAfterContentChecked() { 
    if (this._nativeElem !== undefined) 
     // childContent ref is undefined 
     console.log(this.someHndl); 
     // markup is in the DOM 
     console.log(this._nativeElem.querySelectorAll('#forViewRef')); 
} 
+0

见无法创建VIewRef。你想要达到什么目的? – yurzui

+0

我注入模板的动态标记包含带有Id属性的div。我期望选择这些div ID来生成ViewContainerRef并进一步注入动态组件。 – Chris

+0

您可以使用'appendChild'创建组件并将其插入到某个位置 – yurzui

回答

2

要创建组件d ynamically内<div id="forViewRef"></div>你可以做到以下几点:

比方说,我们需要加载以下组件

@Component({ 
    selector: 'dynamic-comp', 
    template: ` 
    <h2>Dynamic component</h2> 
    <button (click)="counter = counter + 1">+</button> {{ counter }} 
    ` 
}) 
export class DynamicComponent { 
    counter = 1; 
} 

所以首先把它添加到declarations,之后entryComponents阵列的你@NgModule

... 
    declarations: [ ..., DynamicComponent ], 
    entryComponents: [ DynamicComponent ], 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { } 

创建

template.html

<button (click)="createComponent()">Create component</button> 

<div id="forViewRef"></div> 

最后写

component.ts

export class AppComponent { 
    compRef: ComponentRef<DynamicComponent>; 

    constructor(private injector: Injector, 
       private resolver: ComponentFactoryResolver, 
       private appRef: ApplicationRef) {} 


    createComponent() { 
    const compFactory = this.resolver.resolveComponentFactory(DynamicComponent); 
    this.compRef = compFactory.create(this.injector, null, '#forViewRef'); 

    this.appRef.attachView(this.compRef.hostView); 
    } 

    ngOnDestroy() { 
    if(this.compRef) { 
     this.compRef.destroy(); 
    } 
    } 
} 

我使用appRef.attachView以包括动态分量来改变检测周期

Plunker Example