[英]Angular2 passing variables between components
我有以下組件:
@Component({
selector: 'myselector',
providers: [ ],
directives: [ ChildComponent],
pipes: [ ],
template: '<myselector>This is {{testEmitter}}</myselector>'
})
export class ParentComponent{
@Input() testEmitter;
constructor(){
}
}
//My Child class goes as such:
@Component({
selector: 'childselector',
templateUrl: '<childselector><input type="text" (focus)="beginTest()"/></childselector>',
pipes: [],
directives: []
})
export class ChildComponent{
@Output() testEmitter: EventEmitter = new EventEmitter();
startTest: boolean = false;
constructor() {
}
beginTest(){
this.startTest = !this.startTest;
this.testEmitter.emit(this.startTest);
}
}
我只是想弄清楚如何顯示從ChildComponent到ParentComponent的this.startTest
變量的值。 目前, {{testEmitter}}
在我的ParentComponent html中沒有顯示任何內容。 我覺得我接近了。 感謝您的幫助!
這段代碼似乎沒有多大意義。
@Component({
selector: 'myselector',
providers: [ ],
directives: [ ChildComponent],
pipes: [ ],
template: '<myselector>This is {{testEmitter}}</myselector>'
})
模板使用其模板的組件的選擇器<myselector>
。 盡管在某些情況下這是有意義的(例如樹之類的遞歸結構),但這似乎並不是這里的意圖。
@Component()
上的directives
和pipes
也已經消失了一段時間,應該改為添加到@NgModule()
。 顯然,您使用的是beta或RC版本,而不是仍支持Angular2的final版本。 我建議更新到最新的Angular2版本。
這可能是您想要的:
@Component({
selector: 'parentselector',
directives: [ChildComponent],
template: '<childselector (testEmitter)="testEmitter=$event">This is {{testEmitter}}</childselector>'
})
export class ParentComponent{
@Input() testEmitter;
}
@Component({
selector: 'childselector',
templateUrl: '<input type="text" (focus)="beginTest()"/>',
})
export class ChildComponent{
@Output() testEmitter: EventEmitter = new EventEmitter();
startTest: boolean = false;
beginTest(){
this.startTest = !this.startTest;
this.testEmitter.emit(this.startTest);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.