简体   繁体   English

如何在Angular 2中使用一个类(组件)的变量在另一个类(组件)中?

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

I am using Angular 2 (TypeScript). 我正在使用Angular 2(TypeScript)。 To make it simple, there are two files: A.ts and B.ts . 为简单A.ts ,有两个文件: A.tsB.ts

How to use AAA(in A.ts) in the class of B.ts? 如何在B.ts类中使用AAA(在A.ts中)? Thanks! 谢谢! I spent over a day, but still have not succeeded... 我花了一天的时间,但仍然没有成功...

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 ts

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

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

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

It depends on relations between your components: 这取决于组件之间的关系:

  1. If you use a component A inside of a view of a component C you can use @ViewChild property decorator to get reference to the A component (you'll can use A component only after afterViewInit lifecycle hook will be called). 如果在组件C 的视图内使用组件A ,则可以使用@ViewChild属性修饰符来获取对A组件的引用(只有在afterViewInit生命周期挂钩之后,才能使用A组件)。

  2. If you use a component B as a content of a component B you can use @ContentChild property decorator to get reference to the B component (you'll can use B component only after afterContentInit lifecycle hook will be called). 如果你使用一个组件B 作为成分的含量 B可以用@ContentChild财产装饰让参照B组件(你可以用B组件后,才afterContentInit生命周期挂钩将被调用)。

  3. If you want to get the component where your component is located, you can use @Host() and @Inject() parameter decorators. 如果要获取组件所在的组件,则可以使用@Host()@Inject()参数修饰符。

Take a look at the next example (see 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!!!'
}

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

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