微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/angularjs/141061.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐