Angular 7 внедряет динамический компонент в шаблон - PullRequest
1 голос
/ 16 июня 2019

У меня есть следующий код. Когда ngOnInit () выполняется, this.widget содержит правильный компонент и this.data содержит соответствующие данные.

Мне не удалось понять, как плавно вставить динамический компонент в шаблон, чтобы результат был эквивалентен , где DynamicComponent - это компонент, на который есть ссылка в this.widget .

Я попробовал несколько онлайн примеров, но не смог заставить их работать. Кто-нибудь может помочь?

import { Component, OnInit, Input } from '@angular/core';
import { IdashService } from '../services/idash.service';

@Component({
  selector: 'app-idash-widget',
  template: `
    <div class="card-body">
      <h5 *ngIf="widgetConfig.title" class="card-title">{{widgetConfig.title}}</h5>

      <!-- I want the component here with the [data] attribute set to this.data -->

    </div>            
  `
})

export class IdashWidgetComponent implements OnInit {

  @Input() widgetConfig;
  widget;
  data;

  constructor(private idashService: IdashService) {
    this.data = {
      someKey: 'someValue'
    }
  }

  ngOnInit() {
    this.widget = this.idashService.moduleConfig.widgets[this.widgetConfig.type];
    console.warn(this.widget, this.data)
  }

}

1 Ответ

2 голосов
/ 16 июня 2019

Попробуйте приведенный ниже код, чтобы увидеть, работает ли он

<template #dynamicContainer></template>

И в вашем компоненте

@ViewChild("dynamicContainer", { read: ViewContainerRef }) container: ViewContainerRef;
componentRef: ComponentRef<DynamicComponent>;
constructor(private resolver: ComponentFactoryResolver) {}

createComponent(type) {
    //Clear the container.
    this.container.clear();
    //Create a factory for component.
    const factory = this.resolver.resolveComponentFactory(DynamicComponent);
    //Create a component using the factory
    this.componentRef = this.container.createComponent(factory);
    //Pass the value for @Input properties using a component reference instance method.
    this.componentRef.instance.data = this.data;
}

В вашем модуле обязательно добавьте свой компонент в массив entryComponents, как этот

entryComponents: [GaugeComponent]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...