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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With