テンプレートに動的に挿入されたマークアップから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'));
}
も参照してください。あなたは何をしようとしていますか? – yurzui
テンプレートに注入する動的マークアップには、Id属性を持つdivが含まれています。これらのdiv IDに対してViewContainerRefを生成し、さらに動的コンポーネントを注入することを期待しました。 – Chris
コンポーネントを作成し、 'appendChild'を使ってどこかに挿入することができます – yurzui