I'm attempting to create a straightforward Angular2
Application with TypeScript
. Despite its apparent simplicity, I'm struggling to achieve my desired outcome.
My goal is to display a property value in the template and then update it after 1 second using setTimeout.
You can view the code on Plunkr here: Code on Plunkr
The snippet of code I've written looks like this:
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);
}
Upon running this code, I'm encountering the following error:
Uncaught SyntaxError: Unexpected token ;
I'm puzzled as to why I cannot access n
, especially since it should be within the same scope, similar to JavaScript. From what I understand, TypeScript supports regular JavaScript syntax too.
I also attempted the following:
export class AppComponent {
public n : number = 1;
console.log(n);
}
However, I was unable to see the value of n
in the console.
Another attempt was made with:
export class AppComponent {
public n : number = 1;
console.log(this);
}
But I received the same error as before. It's confusing why we can't access 'this' in this context when, traditionally in Javascript, 'this' refers to the current context.