5

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

3
  • How are you instantiating testModels? Commented Oct 25, 2016 at 8:49
  • 1
    Where does the TestModel instance come from? From JSON? Commented Oct 25, 2016 at 8:49
  • Yep it's actually a web service. I'll update the code example to show Commented Oct 25, 2016 at 8:49

2 Answers 2

5

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Günter Zöchbauer
1

you can add a getter to your typescript class

export class Person {
    firstname: string;
    lastname: string;
    get name(): string {
        return `${this.firstname} ${this.lastname}`;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.