如何在 Angular 2 中的另一个 class(component) 中使用一个 class(component) 的变量?

How to use variable of one class(component) in another class(component) in Angular 2?

我正在使用 Angular 2 (TypeScript)。为了简单起见,有两个文件:A.tsB.ts.

如何在B.ts的class中使用AAA(in A.ts)?谢谢!折腾了一天多,还是没有成功...

A.ts

import {Component, View} from 'angular2/angular2';

@Component({
    selector: 'foo'
})
@View({
    template:`

    `
})
export class Foo{
    AAA:DataClass = new DataClass(); // AAA is here.
}

B.ts

import {Component, View} from 'angular2/angular2';

@Component({
    selector: 'bar'
})
@View({
    template:`

    `
})
export class Bar{
    constructor(){
        // How can I use AAA here?
    }
}

这取决于你的组件之间的关系:

  1. 如果您在组件 C 的视图 中使用组件 A ,您可以使用 @ViewChild property decorator to get reference to the A component (you'll can use A component only after afterViewInit将调用生命周期钩子)。

  2. 如果你使用组件B 作为组件B的内容你可以使用@ContentChild property decorator to get reference to the B component (you'll can use B component only after afterContentInit生命周期钩子将被调用)。

  3. 如果你想获取你的组件所在的组件,可以使用@Host() and @Inject()参数装饰器。

看看下一个例子(见this plunk):

import {Component, ViewChild, ContentChild, Host, Inject, forwardRef} from 'angular2/angular2'

@Component({ selector: 'a-cmp' /* ... */ })
class A {
  greet = 'Hello, I\'m A!!!'
}

@Component({ selector: 'b-cmp' /* ... */ })
class B {
  greet = 'Hello, I\'m B!!!'
}

@Component({
  selector: 'c-cmp',
  directives: [A],
  template: '<a-cmp></a-cmp><ng-content></ng-content><div>c-template</div>'
})
class C {
  @ViewChild(A) a: A;
  @ContentChild(B) b: B;

  constructor(@Host() @Inject(forwardRef(() => App)) app: App) {
    console.log(app.greet);
  }
  afterViewInit() {
    console.log(this.a.greet);
  }
  afterContentInit() {
    console.log(this.b.greet);
  }
}

@Component({
  selector: 'my-app',
  directives: [B, C],
  template: '<c-cmp><b-cmp></b-cmp></c-cmp>'
})
export class App {
  greet = 'Hello, I\'m App!!!'
}