首页 > 解决方案 > 在 Angular 5 中渲染任意组件

问题描述

我查看了很多问题,但没有找到我正在尝试做的事情的答案。抱歉,如果我错过了什么。

基本上我需要的是一个组件,它可以在不事先知道的情况下渲染任何其他任意组件,如下所示:

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>,但是我将如何指定它属于哪一个呢?有没有办法做到这一点或达到最终结果?

标签: angularangular5

解决方案


    <ng-content select="[card-body]"></ng-content>

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

如果您只想指定位置,请查看这是否对您有帮助。


推荐阅读