我正在动态加载组件,但未处理子组件。 嵌套的组件在运行时已解析。
是否需要采取其他措施,还是必须为所有嵌套节点(例如根节点)创建组件?
TS:
@Component({
selector: 'test-a',
template: `<ng-content></ng-content>`,
})
export class A {
}
---
@Component({
selector: 'test-b',
template: `<ng-content></ng-content>`,
})
export class B {
}
---
const el = window.document.getElementById('test');
const elA = window.document.createElement('test-a');
const elB = window.document.createElement('test-b');
const elC = window.document.createElement('hello');
elC.setAttribute('name', '{{ name }}')
elC.innerText = 'placeholder';
elB.appendChild(elC);
elA.appendChild(elB);
el.appendChild(elA);
const node = Array.from(el.childNodes)[0];
const resolver = injector.get(ComponentFactoryResolver);
const factory = resolver.resolveComponentFactory(A);
const ngComponent = factory.create(injector, [ Array.from(node.childNodes) ], node);
appRef.attachView(ngComponent.hostView);
查看:
<div _ngcontent-c112="" id="test">
<test-a ng-version="7.0.1">
<test-b>
<hello name="{{ name }}">placeholder</hello>
</test-b>
</test-a>
</div>
Stackblitz示例: https://stackblitz.com/edit/angular-n5yh1d