How to append node dynamically and create component in this node

44 views
Skip to first unread message

Paul Belowee

unread,
Jul 15, 2016, 10:58:16 AM7/15/16
to AngularJS
I have a component. I need locate node in the template, append child node to located node and dynamically create some component inside the child node.

Is it possible with Angular 2?

If the node exists in the template statically the solution is known.

export class AppComponent {
  @ViewChild("node", { read: ViewContainerRef }) nodeView;

..............

  ngOnInit(): void {
    this. componentResolver.resolveComponent(MyComponent)
      .then((factory: ComponentFactory<MyComponent>) => {
         MyComponent instance = this.nodeView.createComponent(factory);
       });
  }
}

In that way the problem is to find dynamic equivalent of @ViewChild directive.

p. stephen w

unread,
Jul 18, 2016, 1:03:27 PM7/18/16
to AngularJS
I'm not 100% clear on your needs, but let me try anyway.  It sounds to me like you need nested components.  You could nest your components within each other with an *ngIf on them to control their display.  Instead of searching the dom tree for them, you toggle a boolean property to display them.

Hopefully, that helps.

Paul Belowee

unread,
Jul 22, 2016, 4:47:17 AM7/22/16
to AngularJS
Yes we are using this solution now.
But it is not the nice solution. We are planning to use up to 100-200 components depending on user rights.
Reply all
Reply to author
Forward
0 new messages