Angular:在内容投影时获取对父组件的引用
在我的情况下,我有一个组件,如果它在特定组件内,应该表现不同.所以我想通过父母来查找正确类型的组件,在简单的情况下通过依赖注入很好地工作:
子组件 @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); } } 父组件 @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; } 用法,有效 <spike-parent [id]="1"> <spike-child></spike-child> </spike-parent> 不幸的是,如果我们通过内容投影添加一个间接,这不再起作用了: ProjectedContent组件 @Component({ selector: 'spike-projected-content',template: '<spike-parent [id]="2"><ng-content></ng-content></spike-parent>' }) export class ProjectedContentComponent { } 用法,不起作用 <spike-projected-content> <spike-child></spike-child> </spike-projected-content> 显然,子节点在运行时将再次位于父节点内,但现在它总是作为注入参数获取null.我理解投射的内容会保留原始上下文(包括注入链),这肯定几乎总是有用,但有没有办法解决这种情况?我读到了关于ngComponentOutlet的看起来可能会有所帮助,但我并没有完全看出它是如何适合的.我也没有发现任何从这种情况中采取最后一步的问题.我想我可以查询DOM来实现结果,但我显然想避免这种情况并使用Angular技术. 非常感谢!
我只能看到两种方式(DOM黑客攻击除外):
>切换到使用模板.故障单仍处于打开状态:14935.目前无法在viewContainerRef.createEmbeddedView中覆盖注入器,但是可以选择传递上下文信息(示例context-parameter-in-angular,或使用NgTemplateOutlet).>使用DI可以查找投影的子组件并调用其方法.每个子组件使用公共标记{provide:Token,useExisting:forwardRef(()=> Child)}提供自身,它允许使用@ContentChildren(Token)并获取所有预计子项的列表,并调用任何方法/ setter. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |