我看过很多问题,并没有找到我想要做的答案。如果我错过了什么,请道歉。
基本上我需要的是一个组件,它可以在不事先知道任何其他任意组件的情况下呈现,如下所示:
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>
一样传递标签,但是我如何指定它属于哪一个?有没有办法做到这一点或达到最终结果?
答案 0 :(得分:0)
<ng-content select="[card-body]"></ng-content>
https://scotch.io/tutorials/angular-2-transclusion-using-ng-content
如果您只想指定位置,请查看这是否有帮助。