Jurgen Welschen Jurgen Welschen - 1 year ago 332
TypeScript Question

Angular2, view not updating after variable changes in settimeout

I am trying to setup my first angular2 application as an experiment and am using the latest beta release.

I am facing a weird issue where the variable i am using in my view is not being updated after setting a timeout.

selector: "my-app",
bindings: []

templateUrl: "templates/main.component.html",
styleUrls: ['styles/out/components/main.component.css']

export class MainComponent {

public test2 = "initial text";

constructor() {
setTimeout(() => {
this.test2 = "updated text";
}, 500);


As you can see i have a variable named test2 and in the constructor i set a timeout of 500 ms where i am updating the value to "updated text".

Then in my view main.component.html i simply use:

{{ test2 }}

But the value will never be set to "updated text" and stays on "initial text" forever even though the update part is being hit. If i follow the angular2 tutorial they dont really give me an answer to this solution. Was wondering if anyone would have an idea of what i am missing here.

edit: my full code i am using including the bootstrap and html etc

<title>Angular 2</title>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="/node_modules/reflect-metadata/reflect.js"></script>
<script src="/node_modules/angular2/bundles/angular2.dev.js"></script>

<script src="/node_modules/q/q.js"></script>
<script src="/node_modules/jquery/dist/jquery.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="/bower_components/breeze-client/breeze.debug.js"></script>
<script src="/bower_components/datajs/datajs.js"></script>
<script src="/bower_components/bootstrap-less/js/collapse.js"></script>
<script src="/bower_components/bootstrap-less/js/modal.js"></script>

<script src="/bower_components/signalr/jquery.signalR.js"></script>
<script src="http://localhost:64371/signalr/js"></script>

<link href="styles/out/main.css" type="text/css" rel="stylesheet" />
map: {
rxjs: '/node_modules/rxjs' // added this map section
packages: {'scripts/out': {defaultExtension: 'js'}, 'rxjs': {defaultExtension: 'js'}}



main.ts with the bootstrap:

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser'
import {COMMON_DIRECTIVES} from './constants';
import {MainComponent} from './components/main.component'


{{ test2 }}

Answer Source

As Vlado said, it should work ;-)

I think that the angular2-polyfills.js library should be included into your page. I can't see it. This file is essentially a mashup of zone.js and reflect-metadata. Zones take part of the detection of updates.

You could have a look at this video where Bryan Ford explains what it is: https://www.youtube.com/watch?v=3IqtmUscE_U.

Hope it helps you, Thierry

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download