2015-11-13 36 views
0

我正在使用Angular 2(TypeScript)。爲了簡單起見,有兩個文件:A.tsB.ts如何在Angular 2的另一個類(組件)中使用一個類(組件)的變量?

如何在B.ts的類中使用AAA(在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? 
    } 
} 

回答

3

這取決於你的組件之間的關係:

  1. 如果您使用co mponent AC可以使用@ViewChild財產裝飾得到參考A組件的組件的視圖內(你只能使用後afterViewInit生命週期掛鉤將被調用A組件)。

  2. 如果您使用組件B爲成分的含量B可以使用@ContentChild財產裝飾得到參考B組件(你只能使用後afterContentInit生命週期掛鉤將被調用B組件) 。

  3. 如果要獲取組件所在的組件,可以使用參數裝飾器@Host()@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!!!' 
} 
+0

謝謝,alexpods,這是一個非常詳細和完整的幫助。我會先試着讓你知道結果! –

+0

謝謝,alexpods,感覺就像我有很多東西要學習! –

相關問題