簡體   English   中英

如何在Angular 2中使用一個類(組件)的變量在另一個類(組件)中?

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

我正在使用Angular 2(TypeScript)。 為簡單A.ts ,有兩個文件: A.tsB.ts

如何在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.
}

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屬性修飾符來獲取對A組件的引用(只有在afterViewInit生命周期掛鈎之后,才能使用A組件)。

  2. 如果你使用一個組件B 作為成分的含量 B可以用@ContentChild財產裝飾讓參照B組件(你可以用B組件后,才afterContentInit生命周期掛鈎將被調用)。

  3. 如果要獲取組件所在的組件,則可以使用@Host()@Inject()參數修飾符。

請看下一個示例(請參閱示例):

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