[英]Angular 8: Have One Variable Subscribe to another variable in 1 Component class
[英]How to use variable of one class(component) in another class(component) in Angular 2?
我正在使用Angular 2(TypeScript)。 為簡單A.ts
,有兩個文件: A.ts
和B.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?
}
}
這取決於組件之間的關系:
如果在組件C
的視圖內使用組件A
,則可以使用@ViewChild
屬性修飾符來獲取對A
組件的引用(只有在afterViewInit
生命周期掛鈎之后,才能使用A
組件)。
如果你使用一個組件B
作為成分的含量 B
可以用@ContentChild
財產裝飾讓參照B
組件(你可以用B
組件后,才afterContentInit
生命周期掛鈎將被調用)。
請看下一個示例(請參閱此示例):
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.