Reputation: 23
I'm a newbie and not even sure if my issue is a Typescript or Angular2 misunderstanding...
I have the following code (reduced to the minimum):
import {OnInit, Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
@Component({
selector: 'hello-app',
template: `
<h1>Foo:{{foo}}</h1>
`
})
export class HelloApp implements OnInit {
foo: string;
ngOnInit() {
this.loadFoo();
}
loadFoo()
{
this.loadInput(function(input: string) {
this.foo = input;
})
}
loadInput (callback) {
callback ("bar");
}
}
bootstrap(HelloApp);
Once transcripted and ran in my browser I get the following error message in the browser debugger:
angular2.min.js:17 TypeError: Cannot set property 'foo' of undefined
at hello.js:34
at HelloApp.loadInput (hello.js:38)
at HelloApp.loadFoo (hello.js:31)
at HelloApp.ngOnInit (hello.js:28)
at e.ChangeDetector_HostHelloApp_0.detectChangesInRecordsInternal (viewFactory_HostHelloApp:21)
at e.detectChangesInRecords (angular2.min.js:6)
at e.runDetectChanges (angular2.min.js:6)
at e.detectChanges (angular2.min.js:6)
at t.detectChanges (angular2.min.js:4)
at angular2.min.js:9
Anyone know why "this" is undefined here and what's my option to set up what goes in {{foo}} using the callback method ?
Thanks !
Upvotes: 0
Views: 115
Reputation: 202326
You need to use an arrow function so you will be able to use the lexical this
keyword:
this.loadInput((input: string) => {
this.foo = input;
});
See this link for more hints about the lexical this of arrow functions:
Upvotes: 1