我已经看了很多问题,但没有找到我想要做的事情的答案。如果我错过了什么,很抱歉。
基本上我需要的是一个组件,可以渲染任何其他任意组件,而不需要事先知道它,如下所示:
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>一样传递标记,但是我如何指定它属于哪个组件呢?有没有办法做到这一点或达到最终结果?
发布于 2018-06-03 01:17:02
<ng-content select="[card-body]"></ng-content>https://scotch.io/tutorials/angular-2-transclusion-using-ng-content
如果您只想指定位置,请查看这是否对您有帮助。
https://stackoverflow.com/questions/50658630
复制相似问题