I'm just starting with Angular2, reading the official docs. 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. 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
. at the time when setTimeout
callback runs, this
doesn't point to the component anymore. you might want to check a bit about javascript this problem
.
try:
setTimeout(()=>{
this.data = "new text";
},5000);
You forgot to import the OnInit interface and make your component implement it.
import { Component, OnInit } from '@angular/core';
And then
export class MainComponent implements OnInit { ... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.