将模板投射到 Angular 中的远方后代
project a template to a distant descendant in Angular
I have a container that use a component (a).
Component a using a component b.
Component b using a component c.
... Component n using a component n+1.
我的模板将显示在 n+1 组件中,有没有办法直接投影到该组件,而无需通过所有组件链接它?
根据少量信息,我怀疑您想要以下内容:
<hello>
This is projected
</hello>
其中 this is projected
将投影到 hello
组件的孙子。
这可以使用 ng-template
和 ng-content
元素轻松完成,使用 ViewChild
获得 TemplateRef
然后注入 parent孙子组件中的组件。另一种方法是使用服务,但思路是一样的:
Parent:
@Component({
selector: 'hello',
template: `
<ng-template>
<ng-content></ng-content>
</ng-template>
<hello2></hello2>
`
})
export class HelloComponent {
@ViewChild(TemplateRef, { static: true })
template?: TemplateRef<any>
}
Child:
@Component({
selector: 'hello2',
template: `<hello3></hello3>`
})
export class Hello2Component {}
盛大Child:
@Component({
selector: 'hello3',
template: `
<ng-container [ngTemplateOutlet]="hello.template"></ng-container>
`
})
export class Hello3Component {
constructor(readonly hello: HelloComponent) {}
}
I have a container that use a component (a).
Component a using a component b.
Component b using a component c.
... Component n using a component n+1.
我的模板将显示在 n+1 组件中,有没有办法直接投影到该组件,而无需通过所有组件链接它?
根据少量信息,我怀疑您想要以下内容:
<hello>
This is projected
</hello>
其中 this is projected
将投影到 hello
组件的孙子。
这可以使用 ng-template
和 ng-content
元素轻松完成,使用 ViewChild
获得 TemplateRef
然后注入 parent孙子组件中的组件。另一种方法是使用服务,但思路是一样的:
Parent:
@Component({
selector: 'hello',
template: `
<ng-template>
<ng-content></ng-content>
</ng-template>
<hello2></hello2>
`
})
export class HelloComponent {
@ViewChild(TemplateRef, { static: true })
template?: TemplateRef<any>
}
Child:
@Component({
selector: 'hello2',
template: `<hello3></hello3>`
})
export class Hello2Component {}
盛大Child:
@Component({
selector: 'hello3',
template: `
<ng-container [ngTemplateOutlet]="hello.template"></ng-container>
`
})
export class Hello3Component {
constructor(readonly hello: HelloComponent) {}
}