Search code examples
angularstring-interpolation

Angular pass in string from .ts file for (click) handler in .html file


I am creating a list of menu items, like so:

<ul>
  <li *ngFor="let item of menuItems" (click)="item.handler">
    <div>{{item.label}}</div> 
  </li>
</ul>

and I want to pass in the function to use as the click handler from the ts file, like so:

constructor(){
    this.menuItems = [
      {label: 'HOME', handler: 'homeHandler()'},
      {label: 'VIEW', handler: 'viewHandler()'}
    ]
  }

  homeHandler() {
    console.log('homeHandler called');
  }

  viewHandler() {
    console.log('viewHandler called');
  }

The label works as expected, but the click functions never get called. What am I doing wrong?


Solution

  • Handler cannot be a string, and it is in your case. This should make much more sense:

    <ul>
      <li *ngFor="let item of menuItems" (click)="item.handler()">
        <div>{{item.label}}</div> 
      </li>
    </ul>
    
    
    
    constructor(){
        this.menuItems = [
          {label: 'HOME', handler: this.homeHandler.bind(this)},
          {label: 'VIEW', handler: this.viewHandler.bind(this)}
        ]
      }
    
      homeHandler() {
        console.log('homeHandler called');
      }
    
      viewHandler() {
        console.log('viewHandler called');
      }
    

    notice how handlers are function objects now not strings and those are called from the view