Рендеринг компонента динамически - PullRequest
3 голосов
/ 28 марта 2019

У меня есть этот массив:

this.dashboard = [
     {name: '<app-incassi-provvigioni></app-incassi-provvigioni>'},
     {name: '<app-scheda-punti-vendita></app-scheda-punti-vendita>'}
]

Я заполняю этот массив в цикле ngOnInit.Мне было интересно, как я могу визуализировать компоненты, когда я читаю свой массив в HTML следующим образом:

<gridster [options]="gridsterOptions">
    <gridster-item [item]="item" *ngFor="let item of dashboard">
        <!-- your content here -->
        {{item.name}}
    </gridster-item>
</gridster>

Конечно, сейчас он возвращает строку, содержащуюся в объекте, но я пытаюсь найти решениевизуализировать компонент.Возможно ли это сделать?

Подробнее: я занимаюсь разработкой приложения типа панели мониторинга, в котором я получаю список пользовательских панелей мониторинга из БД и пытаюсь динамически визуализировать эти компоненты, как только основной компонент приложенияготов.используя Angular 7 & Gridster2.

Ответы [ 4 ]

0 голосов
/ 28 марта 2019

Вы можете ввести компонент динамически

Просто создайте компонент с помощью компонента @Input ();

export class DynamicContentComponent implements OnInit {

  @Input() component: any;
  @Input() data: any;

  constructor(public viewContainerRef: ViewContainerRef,
              private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.component);
    this.viewContainerRef.clear();

    const componentRef = this.viewContainerRef.createComponent(componentFactory);
    (<DynamicComponentRef>componentRef.instance).data = this.data;
  }
}

И используйте его в HTML

<app-dynamic-content [component]="someComponent" [data]="data"></app-dynamic-content>

Пример данных

someComponent = SchedaPuntiVendita;

Динамические компоненты должны быть добавлены к entryComponents в вашем module

Также вы можете создать некий factory, который получит некоторую строку и в зависимости от того, вернет ли вам класс компонента

Пример фабрики

@Injectable()
export class DynamicContentComponentFactory {

  constructor() { }

  get(type: ContentType): any {
    switch (type) {
      case 'scheda':
        return SchedaPuntiVendita;
    }
  }

и изменить DynamicContentComponent немного

@Input() contentType: string;

constructor(..., private factory: DynamicContentComponentFactory) { }
...

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.factory.get(this.contentType));

...
0 голосов
/ 28 марта 2019

скорее передайте имя тега компонента («app-incassi-provvigioni» в вашем случае), передайте имя компонента (TestComponenet), затем вызовите функцию из вашего представления и отобразите ее динамически с помощью Directive.

например:

<gridster [options]="gridsterOptions">
    <gridster-item [item]="item" *ngFor="let item of dashboard">
        <div class="inner">
    <ng-template dynamic-template> </ng-template>
</div>
    </gridster-item>
</gridster>

dynamic-template - это директива, которая помогает нам загружать компонент.

0 голосов
/ 28 марта 2019
this.dashboard = [
         {name: 'dashboard1'},
         {name: 'dashboard2'}
    ]

    <gridster [options]="gridsterOptions">
        <gridster-item [item]="item" *ngFor="let item of dashboard">
            <ng-container *ngIf="item.name === 'dashboard1'" *ngTemplateOutlet="dashboard1">
            </ng-container>
            <ng-container *ngIf="item.name === 'dashboard1'" *ngTemplateOutlet="dashboard2">
            </ng-container>
        </gridster-item>
    </gridster>


    <ng-template #dashboard1>
        <app-incassi-provvigioni></app-incassi-provvigioni>
    </ng-template>
    <ng-template #dashboard2>
        <app-scheda-punti-vendita></app-scheda-punti-vendita>
    </ng-template>
0 голосов
/ 28 марта 2019

Может быть, вы можете использовать угловой переключатель для этого:

<div [ngSwitch]="item.name">
    <app-incassi-provvigioni *ngSwitchCase="incassi"></app-incassi-provvigioni>
    <app-scheda-punti-vendita *ngSwitchCase="scheda"></app-scheda-punti-vendita>
</div>
...