简体   繁体   English

更新了Angular2中@Parent()的语法

[英]Updated Syntax for @Parent() in Angular2

I am looking at a sample for angular2 where a class constructor references @Parent(). 我正在看一个angular2的示例,其中的类构造函数引用了@Parent()。 I get a Error:(58, 18) TS2304: Cannot find name 'Parent'. 我收到错误消息:(58,18)TS2304:找不到名称“父母”。 I saw another answered questioned that said to use 'Host' but I got the same error. 我看到另一个回答的问题,说要使用“主机”,但是我遇到了同样的错误。 I'm using Alpha.45. 我正在使用Alpha.45。 Here is a reference to the sample. 是对示例的参考。 Full code is at the end. 完整的代码在结尾。

constructor(@Parent() tabs:Tabs) {
        tabs.addTab(this);
        this._active=true ;
    }

@Host parameter decorator just restrict the dependency resolution with the host component. @Host参数修饰器仅限制与主机组件的依赖项解析。 You don't have to use it to get the closest component of specified Type. 您不必使用它来获取指定类型的最接近的组件。 However, you may need to use @Inject with forwardRef if your dependency isn't yet defined. 但是,如果尚未定义依赖项,则可能需要将@InjectforwardRef一起使用。

For example (see this plunk , I don't use forwardRef there): 例如(请参阅此小插曲 ,我在那里不使用forwardRef ):

import {Component, Input, Inject, forwardRef} from 'angular2/angular2'

@Component({
  selector: 'tab',
  template: 'Tab {{ index }}'
})
class Tab {
  @Input() index: number;

  constructor(@Inject(forwardRef(() => Tabs)) tabs: Tabs) {
    console.log(tabs);
  }
}

@Component({
  selector: 'tabs',
  template: 'Tabs (<ng-content></ng-content>)'
})
class Tabs {}

@Component({
  selector: 'my-app',
  directives: [Tabs, Tab],
  template: `
    <tabs>
      <tab index="1"></tab>
      <tab index="2"></tab>
    </tabs>
  `
})
export class App {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM