Home > Mobile >  Dynamic onClick over void functions on iteration from HTML in Angular
Dynamic onClick over void functions on iteration from HTML in Angular

Time:04-08

I´ve been wondering if is possible to set in an object some items with values being void functions, thus once this object is iterated in HTML, on a click i could trigger those methods functionalities.

Lets say i have two methods

public method1():void{
   ...do something
},

public method2():void{
   ...do something
}

then i create an object containing this to methods of type void:

const objArray=[
  {click:this.method1()},
  {click:this.method2()}
]

then the idea would be to iterate over this array of objects in the HTML and trigger its functionality

HTML

<ul >
    <span *ngFor="let item of objArray">
      <a
        (click)="(item.click)"
      > 
      </a>
    </span>
</ul>

on this approach as expected the value of each item is undefined thus I tried to modified the methods array to :

const objArray=[
  {click:()=>this.method1()},
  {click:()=>this.method2()}
]

Still not triggering anything. How can i improve this ? Thanks in advance!

CodePudding user response:

TLDR you forgot brackets in your html

<ul>
  <span *ngFor="let item of objArray">
    <a (click)="item.click()">Click Me</a>
  </span>
</ul>

You can write it this way to assign a reference to the methods:

With this way, any uses of this inside the method will refer to the new object and not your component

const objArray=[
  { click: this.method1 },
  { click: this.method2 }
]

or this way to create a new function that executes the methods:

With this way, this inside the method will refer to your component

const objArray=[
  { click: () => this.method1() },
  { click: () => this.method2() }
]

But in either case you forgot to actually call the function in your html (no brackets)

<ul>
  <span *ngFor="let item of objArray">
    <a (click)="item.click()">Click Me</a>
  </span>
</ul>

Example: https://stackblitz.com/edit/angular-ivy-8awbxg?file=src/app/app.component.ts

  • Related