在Angular中如何检测直接父级并与其进行通信? [英] In Angular How to detect the direct parent and communicate with it?

查看:67
本文介绍了在Angular中如何检测直接父级并与其进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个子组件( child.component ),可以在两个父组件中使用:

I have a child component (child.component) which can be used in two parent components :


  1. parentA.component

  2. parentB.component

  1. parentA.component
  2. parentB.component

在这种情况下,可以制作几个这样的模板:

In this case, it's possible to make several templates like this :

<parentA>
  <child></child>
</parentA>

<parentA>
    <parentB>
       <child></child>
    </parentB>
</parentA>

出于某些原因, child.component 需要检测是否直接

For some reasons, the child.component need to detect if the direct parent is parentB.

我用了'@Inject(forwardRef(()=> parentBComponent))private _directParent:parentBComponent'

I used '@Inject(forwardRef(() => parentBComponent)) private _directParent:parentBComponent'

为此:

export class ChildComponent {
     ...
     constructor(@Inject(forwardRef(() => parentBComponent)) private _directParent:parentBComponent){
         console.dir(_directParent);
     }
}

但是如果 child.component >不是由 parentB.component 包装的,我收到此错误:

But if child.component is not wrapped by parentB.component, I get this error :


例外: http:// localhost:3000 / app / tests / 6.html:5:8 造成原因:ParentBComponent没有提供者!

"EXCEPTION: Error in http://localhost:3000/app/tests/6.html:5:8 caused by: No provider for ParentBComponent!"

我该怎么办?

推荐答案

在某些情况下,解决方案是获取变量 _directParent 可选,这要感谢装饰器 @Optional()

For some cases, the solution is to get the variable _directParent optional thanks the decorator @Optional() :

@Inject(forwardRef(() => parentBComponent)) @Optional() private _directParent:parentBComponent

如果您只有两种情况,并且在一种情况下没有parentBComponent,则该方法有效。
,但没有得到直接的父母,只需让一个具有此组件名称的父母即可。

That works if you have got only two cases and in one case there is no parentBComponent. But THAT DOES NOT GET THE DIRECT PARENT, just get one parent with this component name.

这篇关于在Angular中如何检测直接父级并与其进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆