Визуализация произвольного компонента в Angular 5 - PullRequest
0 голосов
/ 02 июня 2018

Я посмотрел на многие вопросы и не нашел ответа на то, что я пытаюсь сделать.Извиняюсь, если я что-то пропустил.

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

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

class MyWidget {
  name: string;
  content: any; // This could be any component

  constructor(name: string, content: any) {
    this.name = name;
    this.content = content;
  }
}

// Final destination ----------------------------------
@Component({
  selector: 'grandchild',
  template: `
    <h1>{{ myWidget.name }}</h1>
    <!-- render myWidget.content here -->
  `
})
export class GrandchildComponent {
  @Input() myWidget: MyWidget;
}
// ----------------------------------------------------

// Child ----------------------------------------------
@Component({
  selector: 'child',
  template: `
    <div>
      <grandchild *ngFor="let w of myWidgetList" [myWidget]="w"></grandchild>
    </div>
  `
})
export class ChildComponent {
  @Input() myWidgetList: MyWidget[];
}
// ----------------------------------------------------


// Some random components to illustrate ---------------
@Component({
  selector: 'random-foo',
  template: 'I\'m random foo'
})
export class RandomFooComponent {
}

@Component({
  selector: 'random-bar',
  template: 'I\'m random bar'
})
export class RandomBarComponent {
}
// ----------------------------------------------------

@Component({
  selector: 'app-root',
  template: '<child [myWidgetList]="list"></child>'
})
export class AppComponent {
  list = [
    new MyWidget('a', RandomFooComponent),
    new MyWidget('b', RandomBarComponent)
  ];
}

В идеале я бы смогпередать теги так же, как это делается с дочерним компонентом и <ng-content></ng-content>, но как мне указать, к какому из них он принадлежит?Есть ли способ сделать это или достичь конечного результата?

1 Ответ

0 голосов
/ 02 июня 2018
    <ng-content select="[card-body]"></ng-content>

https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

Посмотрите, поможет ли это вам, если вы хотите указать только местоположение.

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