2

My components injected dynamical. But how to define place where they would be without any wrapping?

import { Component, ViewContainerRef, ComponentResolver } from '@angular/core';

  constructor(
    private apiService: ApiService,
    private viewContainerRef: ViewContainerRef,
    private componentResolver: ComponentResolver) {
  }

  create() {
    this.componentResolver.resolveComponent(PieChart).then((factory) => {
      this.viewContainerRef.createComponent(factory);
    });
  }

And i want to inject them in some DIV.

<div class="someClass"> 
<!--How inject them here?  -->
</div>
John Doe
  • 3,794
  • 9
  • 40
  • 72

2 Answers2

2

There are two ways:

  • injecting the ViewContainerRef like in your question, then new components are added below this component

  • using a target element in your components template with a template variable like <div #target></div> and @ViewChild('target', {read: ViewContainerRef}) viewContainerRef:ViewContainerRef; to get the ViewContainerRef of this <div>. Added elements are again added below this <div>

createComponent() allows to pass an index. By default new components are always added at the end, but if you pass an index it is inserted at this position.
(not tested) with index 0 you should be able to add the new element before the target element.
If you add more than one component to the same ViewContainerRef you can pass an index to insert the new component before the elements added earlier.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

In finale release, ComponentResolver is deprecated. Instead, We can use Compiler API to create ComponentFactory.

But how we can do this now?

I found this article http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2-rc-5/ but compiler does not have method compileComponentAsync.

John Doe
  • 3,794
  • 9
  • 40
  • 72