在我的情况下,我有一个组件,如果它在特定组件内,应该表现不同.所以我想通过父母来查找正确类型的组件,在简单的情况下通过依赖注入很好地工作:
子组件
@Component({
selector: 'spike-child',
template: `<div>I am the child, trying to find my parent.
<button (click)="log()">Test</button></div>`
})
export class ChildComponent {
// Get Parent through dependency injection; or null if not present.
public constructor(@Optional() private parent: ParentComponent) { }
public log(): void {
console.log('Parent', this.parent);
console.log('Parent.Id', this.parent && this.parent.id);
}
}
Run Code Online (Sandbox Code Playgroud)
父组件
@Component({
selector: 'spike-parent',
template: `
<div>
<div>I am the parent of the content below, ID = {{ id }}:</div>
<ng-content></ng-content>
</div>`
})
export class ParentComponent {
@Input()
public id: number;
}
Run Code Online (Sandbox Code Playgroud)
用法,有效
<spike-parent [id]="1">
<spike-child></spike-child>
</spike-parent>
Run Code Online (Sandbox Code Playgroud)
不幸的是,如果我们通过内容投影添加一个间接,这不再起作用了:
ProjectedContent组件
@Component({
selector: 'spike-projected-content',
template: '<spike-parent [id]="2"><ng-content></ng-content></spike-parent>'
})
export class ProjectedContentComponent { }
Run Code Online (Sandbox Code Playgroud)
用法,不起作用
<spike-projected-content>
<spike-child></spike-child>
</spike-projected-content>
Run Code Online (Sandbox Code Playgroud)
显然,子节点将在运行时再次位于父节点内,但现在它总是以注入的参数为空.我知道投射的内容会保留原始上下文(包括注入链),这肯定几乎总是有用,但有没有办法解决这种情况?我读到了关于ngComponentOutlet看起来可能会有所帮助,但我并没有看到它是如何适合的.我也没有发现任何从这种情况中采取最后一步的问题.我想我可以查询DOM来实现结果,但我显然想避免这种情况并使用Angular技术.
非常感谢!
我只能看到两种方法(除了 DOM hacking):
viewContainerRef.createEmbeddedView,但是可以选择传递上下文信息(例如context-parameter-in-angular或 use NgTemplateOutlet)。{provide: Token, useExisting: forwardRef(() => Child)},它允许使用@ContentChildren(Token)和获取所有投影子组件的列表,并调用任何方法/设置器。| 归档时间: |
|
| 查看次数: |
2008 次 |
| 最近记录: |