我可以将string或number设置为组件的输入:
@Input('name') name: string;
并在HTML文件中使用它:
<div>{{name}}</div>
但是我想设置component而不是字符串,例如name
换句话说:如何为另一个component的输入设置component?
您不会为此使用input
,您需要将内容投影与ContentChild一起使用。
示例取自Angular Docs:
@Component({
selector: 'example-app',
template: `
<tab>
<pane id="1" *ngIf="shouldShow"></pane>
<pane id="2" *ngIf="!shouldShow"></pane>
</tab>
<button (click)="toggle()">Toggle</button>
`,
})
export class ContentChildComp {
shouldShow = true;
toggle() { this.shouldShow = !this.shouldShow; }
}
[pane
组件,投影在tabs
组件中。
@Component({
selector: 'tab',
template: `
<div>pane: {{pane?.id}}</div>
`
})
export class Tab {
@ContentChild(Pane, {static: false}) pane !: Pane;
}
您可以使用pane
访问tab
组件内的@ContentChild
组件。
[C0的完整指南