2017-05-25 3 views
0

テンプレートに動的に挿入されたマークアップからViewRefを作成したいとします。これは、次のコードサンプルに基づいて可能ですか?角2+マークアップからViewRefを作成して動的テンプレートに挿入

template.html:div要素のinnerHTMLの属性にバインドするAPI呼び出しから

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

注入マークアップ:

<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

も参照してください。あなたは何をしようとしていますか? – yurzui

+0

テンプレートに注入する動的マークアップには、Id属性を持つdivが含まれています。これらのdiv IDに対してViewContainerRefを生成し、さらに動的コンポーネントを注入することを期待しました。 – Chris

+0

コンポーネントを作成し、 'appendChild'を使ってどこかに挿入することができます – yurzui

答えて

2

へコンポーネントdを作成するynamically <div id="forViewRef"></div>の内側には、次の操作を行うことができます

ので、まずその後、あなたの@NgModule

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

declarationsentryComponents配列に追加我々は、以下のコンポーネント

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

をロードする必要があるとしましょう作成

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(); 
    } 
    } 
} 

Iが検出サイクル

Plunker Example

を変更する動的成分を含めるために appRef.attachView使用

あなたはVIewRefを作成することはできません

関連する問題