angular - 在 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>
,但是我将如何指定它属于哪一个呢?有没有办法做到这一点或达到最终结果?
解决方案
<ng-content select="[card-body]"></ng-content>
https://scotch.io/tutorials/angular-2-transclusion-using-ng-content
如果您只想指定位置,请查看这是否对您有帮助。
推荐阅读
- android - ionic cordova build android - 构建失败并出现异常
- json.net - JToken.DeepEquals 支持自动修剪字符串值吗?
- html - dom重新加载时防止默认值不起作用
- c# - Azure 函数上的 FixedDelayRetry 属性无法正常工作
- javascript - 如何滚动到特定元素
- laravel - 在 Laravel 8 中使用 Cloudinary
- java - 解析 JSONObject 时出错
- python - 随机改变调用函数的顺序
- excel - VBA:如何移动每个后续值的值和偏移量
- python - 如果 Python 外部库支持 Python3 的专有特性,它如何不会导致与 Python2 向后兼容的解释器问题?