gpt4 book ai didi

Angular:在进行内容投影时获取对父组件的引用

转载 作者:太空狗 更新时间:2023-10-29 17:20:10 29 4
gpt4 key购买 nike

在我的情况下,我有一个组件,如果它在特定组件内,它的行为应该有所不同。所以我想通过父级查找正确类型的组件,在简单的情况下通过依赖注入(inject)效果很好:

子组件

@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>

很明显,运行时子节点将再次位于父节点内,但现在注入(inject)参数始终为 null。我知道投影的内容会保留原始上下文(包括注入(inject)器链),这绝对几乎总是有帮助的,但是有什么方法可以解决这种情况吗?我阅读了有关 ngComponentOutlet 的信息,它看起来可能有所帮助,但我并不完全了解它如何适合。我也没有发现从这种情况中采取最后一步的任何问题。我想我可以查询 DOM 来获得结果,但我显然想避免这种情况并为此使用 Angular 机制。

非常感谢!

最佳答案

我只能看到两种方式(DOM hacking 除外):

  1. 改用模板。门票仍然开放:14935 .目前无法在 viewContainerRef.createEmbeddedView 中覆盖注入(inject)器,但是可以选择传递上下文信息(例如 context-parameter-in-angular ,或使用 NgTemplateOutlet)。
  2. 使用 DI 能够找到投影的子组件并调用它们的方法。每个子组件使用公共(public) token {provide: Token, useExisting: forwardRef(() => Child)}提供自己,它允许使用@ContentChildren(Token)并获取所有预计 child 的列表,并调用任何方法/setter。

关于Angular:在进行内容投影时获取对父组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51298541/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com