Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular DynamicComponentLoader-如何避免冗余包装器元素?_Angular - Fatal编程技术网

Angular DynamicComponentLoader-如何避免冗余包装器元素?

Angular DynamicComponentLoader-如何避免冗余包装器元素?,angular,Angular,遵循位于的DynamicComponentLoader文档。我知道必须创建包装器元素。在下面的示例中,包装器元素是“子组件” 生成的DOM: <my-app>Parent</my-app> <child-component>Child</child-component> 我的“粗略”代码完成了这项工作,但它似乎与ng2架构不一致。 有没有更好的解决方案来避免使用包装器元素?您可以使用loadAsRoot()函数来满足您的需求 @C

遵循位于的DynamicComponentLoader文档。我知道必须创建包装器元素。在下面的示例中,包装器元素是“子组件”

生成的DOM:

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