ng2:相当于require [英] ng2: Equivalent of require

查看:94
本文介绍了ng2:相当于require的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular 1.x中,我们可以通过在指令中要求它来引用父控制器.但是,使用角度2进行整个命名切换时,我似乎真的找不到与该功能等效的功能吗?

In angular 1.x, we could reference the parent controller by requiring this inside a directive. However, with the whole naming switch-over in angular 2, I cannot really seem to find an equivalent of that functionality?

到目前为止我尝试过的事情:

Things I have tried so far:

  • 我看到的一种方法是将父对象@input到孩子中,但这似乎有点多.
  • 我看到的另一种方式是使用服务,但这使我感到有些恐惧,因为据我所知,服务仍然是单例,因此其他组件现在可能将其他组件的子对象弄得一团糟(如果那样的话)子项引用了该服务)...
  • 最后一次使用的是这些局部变量thingies(带有#标签的事物),但看上去与第一个输入选项相同.

推荐答案

我不太了解Angular1,因此我不知道require的确切功能或用途.

I don't know Angular1 well therefore I can't tell what require does exactly or for what purposes it is used.

对于您的问题中提到的项目符号:

To the bullets mentioned in your question:

  • 通常您使用模板绑定来绑定父级和子级

父模板

<child [childInput]="parentValue" (childOutput)="doSomethingInParent()">

  • 服务是每个提供者的单例.相同的提供程序将始终返回相同的实例,但是您可以多次提供相同的服务,因此它不再是真正的单例.因此,您在何处提供服务定义了将其视为单例的范围.当您在组件上提供该组件时,此组件实例和所有子组件将获得相同的实例(只要没有子组件提供相同的类型).
  • 这种DI行为可以防止像您在问题中提到的那样发生冲突.

    This DI behavior prevents conflicts like you mentioned in your question.

    • 模板变量通常用于指代同级兄弟
    <child1 [child1Input]="child2.child2Prop" 
        (child1Output)="child2doSomethingInChild2()">
    <child2 #child2></child2>
    

    • 如果您知道父组件的类型,则可以要求将其注入到子组件的构造函数中
    • constructor(@Host() private parent:ParentComponent) {}
      

      这在知道父级是什么的递归组件(如树)中尤其方便.在这种情况下,可能需要其他装饰器

      This might especially be handy in recursive components (like tree) where it's know what the parent is. In this case additional decorators might be necessary

      constructor(@Optional() @SkipSelf() @Host() private parent:ParentComponent) {}
      

      哪里

      • @Optional()用于根组件,以避免出现异常,因为没有相同类型的父对象要注入
      • @SkipSelf()当组件与其实际要注入的父对象具有相同的类型时,避免该组件本身被注入. DI总是从组件本身开始,以查找提供程序.
      • @Optional() is for the root component to avoid an exception because there is no parent of the same type to be injected
      • @SkipSelf() avoids the component itself to get injected when it's the same type as the parent it actually wants to get injected. DI always starts on the component itself to look up providers.

      另请参见注入父组件与子组件类型相同

      这篇关于ng2:相当于require的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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