0

I have this code:

menu.component.ts

export class menuComponent {
    menu: object;
    state: boolean;

    constructor() {
        this.state = false;
        this.menu = [
            item: {
                action: this.action
            }
        ]
    }

    action(): void {
        this.state = !this.state;
    }
}

menu.component.html

<ul *ngFor="let item of menu">
    <li>
        <a (click)="item.action()"></a>
    </li>
</ul>

what i need is to use the class functions and attributes inside action function, for example state attribute.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Carlos Ferras
  • 314
  • 2
  • 16
  • 1
    First you need to **call** the function: `(click)="item.action()"`. Then you need to make sure the action is bound to `this`: `action: () => this.action()`or `action: this.action.bind(this)`. – JB Nizet Nov 20 '17 at 19:44
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – JB Nizet Nov 20 '17 at 19:45
  • sorry for the error, i already fix it – Carlos Ferras Nov 20 '17 at 19:52

1 Answers1

1

Although I don't understand why you have a function in state, you can use bind:

    this.menu = [
        item: {
            action: this.action.bind(this)
        }
    ]
smnbbrv
  • 23,502
  • 9
  • 78
  • 109