1

I am trying to create a compoment which is creating dynamically a grid of other components. I am using the Renderer to create div elements.

I am struggling with placing the components at the right place, because the createComponent method of ViewContainerRef always creates the element in itself.

I have also tried to call the create method of the ComponentFactory directly, but I don't know where to add the component instance.

for (let y = 0; y < this.rows; y++) {
  const row: Element = this._renderer.createElement(this._container.element.nativeElement, 'div');
  row.classList.add('row');
  for (let x = 0; x < this.cols; x++) {
    const col = this._renderer.createElement(row, 'div');
    col.classList.add('col-lg-1', 'col-md-1', 'col-xl-1');

    // const template = this._renderer.createTemplateAnchor(col);
    // const view = this._container.createEmbeddedView(template);
    if (configuration !== null) {
      const factory = this._resolver.resolveComponentFactory(component);
      const comp = factory.create(this._container.injector);
      // method not available
      // template.insert(comp.hostView);
      // view.createComponent(factory, 0, this._container.parentInjector, []);
      // Adds component directly to the container
      // this._container.createComponent(factory, 0, this._container.parentInjector, []);
    }
  }
}

Is it possible to do this directly f.e. with creating TemplateRef instances or do I need another directive / component to achieve anything like that?

CSchulz
  • 10,882
  • 11
  • 60
  • 114
  • What is the problem you're actually trying to solve? Why are you not using `*ngFor` to create `
    ` elements? Perhaps a wrapper element like demonstrated in http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 might help in your case for a more Angulary approach.
    – Günter Zöchbauer Feb 21 '17 at 11:15
  • I want to achieve it without a wrapper compoment, f.e. with creating TemplateRef instances on the fly. – CSchulz Feb 21 '17 at 11:44
  • I don't think that's supported. – Günter Zöchbauer Feb 21 '17 at 11:44

0 Answers0