[英]Angular2: when does property binding happen?
I'm just starting with Angular2, reading the official docs. 我只是从Angular2开始,请阅读官方文档。 However, I have not found specific details about how and when the binding happens, and things don't seem to work as I expected.
但是,我还没有找到有关绑定的方式和时间的具体细节,而且事情似乎并没有按我预期的那样工作。
I have a simple child component 我有一个简单的子组件
@Component({
selector: 'dummy',
template: `
<div>{{data}}</div>
`
})
export class Dummy {
@Input() data;
}
and a root component 和根组件
@Component({
selector: 'main',
template: `
<h1>hello</h1>
<dummy [data]="data"></dummy>
`
})
export class MainComponent {
data: string = "initial text";
ngOnInit() {
setTimeout(this.initData, 5000);
}
initData() {
this.data = "new text";
}
}
I would expect the text shown by the child component to change after 5 seconds, however it doesn't. 我希望子组件显示的文本在5秒钟后会更改,但是不会。 What am I doing wrong?
我究竟做错了什么? Does the documentation explain when and under what conditions bound values are initialized and updated?
文档是否说明何时以及在什么条件下绑定值被初始化和更新?
you're losing context of this
. 您将失去
this
。 at the time when setTimeout
callback runs, this
doesn't point to the component anymore. 在当时间
setTimeout
回调运行, this
并不指向组件了。 you might want to check a bit about javascript this problem
. 您可能需要检查一下有关JavaScript的
this problem
。
try: 尝试:
setTimeout(()=>{
this.data = "new text";
},5000);
You forgot to import the OnInit interface and make your component implement it. 您忘记了导入OnInit接口并使组件实现它。
import { Component, OnInit } from '@angular/core';
And then 接着
export class MainComponent implements OnInit { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.