Steven Yates Steven Yates - 1 month ago 63
TypeScript Question

Angular 2 model function interpolation - self.context.$implicit.X is not a function

All,

I am getting an error when trying to bind to a function on a model

I have the following Component, Model & Html (all fake for this example)

export class TestModel {
public getSomeValue(): string {
return "Hello World";
}
}


Let's just assume the testModels property get's it's data somehow.

@Component(...)
public class MyComponent {
public testModels: TestModel[];

ngOnInit() {
this.loadData();
}

public loadData(): void
{
this.http.get("...")
.map(r=>r.json as TestModel[]) // <--- I think now you've asked the question, I see the problem on this line
.subscribe(d=>this.testModels = d);

}
}


Now in my html

<div *ngFor="let testModel of testModels">
<span>{{testModel.getSomeValue()}}</span> <!-- This fails -->
</div>


This is the full error:


error_handler.js:48 EXCEPTION: Error in
./MyComponent class MyComponent- inline template:94:56 caused by:
self.context.$implicit.getSomeValue is not a function


Is is not possible to bind to
.getSomeValue()
or am I doing this wrong?

I'm assuming based on this
self.context.$implicit.
it's loosing it's context somehow and not calling the method on the model but attempting to call it on "it's self" what ever that is?

Thanks

S

EDIT: Added code to show how testModels is instantiated

Answer

as TestModel[] doesn't make it a TestModel. It just tells the typescript compiler (and linter) that it can safely assume that r.json is TestModel[].

See also JSON to TypeScript class instance?

Comments