Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - TypeScript : Increment a number after timeout in AppComponent

I want to create a simple Angular2 Application using TypeScript. Seems, pretty simple, but I am not able to achieve what I wanted to.

I want to show a property value in the template. And I want to update the same after 1 second using setTimeout.

Plunkr Code is here : Code on Plunkr

What I wrote is here :

import {Component} from 'angular2/core';  interface Hero {   id: number;   name: string; }  @Component({   selector: 'my-app',   template:`<h1>Number Increment</h1><p>{{n}}</p>` }) export class AppComponent {   public n : number = 1;   setTimeout(function() {     n = n + 10;   }, 1000); }     

When I use this code I am getting following error :

Uncaught SyntaxError: Unexpected token ; 

Why I am not able to access n, which is in the same scope as we used to do in JavaScript. If I am not wrong, we can use pure JavaScript too in TypeScript.

I even tried

export class AppComponent {   public n : number = 1;   console.log(n); } 

But I am not able to see the value of n in the console.

When I tried

export class AppComponent {   public n : number = 1;   console.log(this); } 

I am getting same error as above. Why cant we access this in this place. I guess, this refers to the current context as in JavaScript.

Thanks in advance.

like image 319
Mahisha Avatar asked Dec 30 '15 12:12

Mahisha


1 Answers

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE export class AppComponent {   public n: number = 1;   setTimeout(function() {     n = n + 10;   }, 1000); } 

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {   public n: number = 1;    constructor() {     setTimeout(() => {       this.n = this.n + 10;     }, 1000);   }  } 

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

like image 67
toskv Avatar answered Sep 18 '22 16:09

toskv