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

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

问题描述

在 angular 1.x 中,我们可以通过在指令中要求 this 来引用父控制器.但是,随着 angular 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 输入到子级中,但这似乎有点多.
  • 我看到的另一种方式是使用服务,但这让我有些恐惧,因为据我所知,服务仍然是单例,所以其他组件现在可能会在不同组件的子组件上搞砸(如果那样的话)孩子引用了该服务)...
  • 最后它使用了这些局部变量(带有主题标签的那些),但这看起来与带有输入的第一个选项相同.

推荐答案

我不太了解 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天全站免登陆