Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self.context is not a function in Angular2 when calling a component function

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?

like image 568
ElSnakeO Avatar asked Aug 08 '16 09:08

ElSnakeO


1 Answers

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>
like image 118
Thierry Templier Avatar answered Nov 14 '22 23:11

Thierry Templier