[typescript] 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.

This question is related to typescript angular

The answer is


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.


You should put your processing into the class constructor or an OnInit hook method.


Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7