Angular 2 Dynamically insert a component into a specific DOM node without using ViewContainerRef

后端 未结 2 1906
长情又很酷
长情又很酷 2020-11-29 06:58

I have a question regarding dynamic component creation in Angular 2 rc5.

So let\'s assume that we have two plain angular components:

  @Component({
          


        
2条回答
  •  臣服心动
    2020-11-29 07:25

    You should never modify DOM outside Angular because it will lead to unpredictable behavior. Even if you append element manually it means nothing because it's not processed by Angular. All changes to DOM inside Angular app have to go through Angular methods.

    Dynamically create a new component:

    @Component({
        selector: 'my-component',
        template: '
    ', }) export class MyComponent { @ViewChild('element', {read: ViewContainerRef}) private anchor: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver) { } whatever() { let factory = this.resolver.resolveComponentFactory(ChildComponent); this.anchor.createComponent(factory); } }

提交回复
热议问题