首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Angular 5中渲染任意组件

在Angular 5中渲染任意组件
EN

Stack Overflow用户
提问于 2018-06-02 23:53:01
回答 1查看 137关注 0票数 1

我已经看了很多问题,但没有找到我想要做的事情的答案。如果我错过了什么,很抱歉。

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

代码语言:javascript
复制
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>一样传递标记,但是我如何指定它属于哪个组件呢?有没有办法做到这一点或达到最终结果?

EN

回答 1

Stack Overflow用户

发布于 2018-06-03 01:17:02

代码语言:javascript
复制
    <ng-content select="[card-body]"></ng-content>

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50658630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档