Hongbo Miao
Hongbo Miao

Reputation: 49694

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

I am using Angular 2 (TypeScript). To make it simple, there are two files: A.ts and B.ts.

How to use AAA(in A.ts) in the class of B.ts? Thanks! I spent over a day, but still have not succeeded...

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?
    }
}

Upvotes: 0

Views: 4278

Answers (1)

alexpods
alexpods

Reputation: 48487

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).

  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).

  3. If you want to get the component where your component is located, you can use @Host() and @Inject() parameter decorators.

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!!!'
}

Upvotes: 3

Related Questions