我想创建一个动态插入模板的标记的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'));
}
见无法创建VIewRef。你想要达到什么目的? – yurzui
我注入模板的动态标记包含带有Id属性的div。我期望选择这些div ID来生成ViewContainerRef并进一步注入动态组件。 – Chris
您可以使用'appendChild'创建组件并将其插入到某个位置 – yurzui