Angular DynamicComponentLoader-如何避免冗余包装器元素?
遵循位于的DynamicComponentLoader文档。我知道必须创建包装器元素。在下面的示例中,包装器元素是“子组件” 生成的DOM:Angular DynamicComponentLoader-如何避免冗余包装器元素?,angular,Angular,遵循位于的DynamicComponentLoader文档。我知道必须创建包装器元素。在下面的示例中,包装器元素是“子组件” 生成的DOM: <my-app>Parent</my-app> <child-component>Child</child-component> 我的“粗略”代码完成了这项工作,但它似乎与ng2架构不一致。 有没有更好的解决方案来避免使用包装器元素?您可以使用loadAsRoot()函数来满足您的需求 @C
<my-app>Parent</my-app>
<child-component>Child</child-component>
我的“粗略”代码完成了这项工作,但它似乎与ng2架构不一致。
有没有更好的解决方案来避免使用包装器元素?您可以使用
loadAsRoot()
函数来满足您的需求
@Component({
selector: 'child-component',
template: 'Child'
})
class ChildComponent {
}
@Component({
selector: 'my-app',
template: 'Parent'
})
class MyApp {
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef, injector: Injector) {
this.dcl.loadAsRoot(ChildComponent, "child-component", this.injector)
}
}
bootstrap(MyApp);
实际的问题是什么?我需要根据JSON规范动态创建组件。但是,我希望保持DOM结构干净。loadAsRoot将把它放在主DOM文档下。我在本地需要它。
<my-app>Parent</my-app>
Child
loadIntoLocation(ChildComponent, cmp, 'child').then(function(ref) {
var elem = ref.location.nativeElement;
ref.instance._nativeElement = elem.firstElementChild; // this._nativeElement instead of this.elementRef.nativeElement
if (elem.parentNode && elem.firstElementChild)
elem.parentNode.replaceChild(elem.firstElementChild, elem);
else
console.log('can not delete Redundent ', elem);
})
@Component({
selector: 'child-component',
template: 'Child'
})
class ChildComponent {
}
@Component({
selector: 'my-app',
template: 'Parent'
})
class MyApp {
constructor(dcl: DynamicComponentLoader, elementRef: ElementRef, injector: Injector) {
this.dcl.loadAsRoot(ChildComponent, "child-component", this.injector)
}
}
bootstrap(MyApp);