7

I want to call a function when I instantiate an angular2 component, but I get the following error: TypeError: self.context.dummyFunc is not a function

The following is a contrived example, but will show you my problem. Assume we have the following component:

import { Component } from '@angular/core';

    @Component({
      selector: 'myItem',
      template: `<div>This will work->{{dummyFunc()}}</div>`,
    })
    export class myItemComponent {
      constructor() { }

      dummyFunc() :string {
        return "bold";
      }
    }

And the following HTML:

<ul myItem [ngClass]='dummyFunc()'></ul>

The following exception will be generated:

TypeError: self.context.dummyFunc is not a function

If i change the HTML to:

<ul myItem></ul>

The component runs and is able to call the dummyFunc function inside the <div>

I am assuming the dummyFunc() is not called in the context of the component myItem, but the component that instantiated myItem.

My question. What would be the proper way to call a function on the just created component when instantiating a component?

2 Answers 2

13

In fact, when you use dummyFunc on the ul element, you are outside the myItem component. So you can't use it. You only have access to properties and methods of the component associated with the current template.

If you want to use a method of a component used in this template, you need to reference it first. You could try the following:

<ul #comp myItem [ngClass]="comp.dummyFunc()"></ul>
Sign up to request clarification or add additional context in comments.

Comments

0

The selector and the attribute need to match

selector: 'myitem',
<ul myItem

Either change the selector to 'myItem' or the attribute to <ul myitem

3 Comments

That was another typo in my question. I should have created the question using my source code, but as the component in question was rather large I opted to try and create an example without using source.. Unfortunately including all the typos. (edited the question)
@Günter Zöchbauer can we use <ul myItem></ul> shouldn't be like <myItem></myItem>
@Danny sorry, but I don't understand your question. The original question was changed since I posted the answer, therefore my answer doesn't really make sense in this context anymore.

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.