【发布时间】:2018-07-12 06:20:54
【问题描述】:
在我的情况下,我有一个组件,如果它位于特定组件中,它的行为应该不同。所以我想通过父母来找到正确类型的组件,在简单的情况下通过依赖注入可以很好地工作:
子组件
@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 机制。
非常感谢!
【问题讨论】:
-
你不能从父级传递一个属性吗?数据流方向相反的感觉很奇怪
-
我对此进行了相当多的研究。写得很好的问题。问题基本上是
spike-parent不是spike-child的父级 - 在组件结构方面。它在 DOM 中,但这只是因为 HTMLElement 可以插入到我们/Angular 选择的任何位置。我认为它们根本不能通过 DI 在父子中引用,因为它们不在父子结构中
标签: angular