Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter onclick, in a loop using angular8

I have an array of objects. i am iterating that in loop and passing each item's name to onclick which targets a function openIt(val) in app.js file which is in assets folder. ie

Angular Code:

<div *ngFor="let item of listArray">
<button class="tabopen" onclick="openIt(item.name)">{{item.name}}</button>
</div>

app.js Code:

function openIt(data) {
console.log(data);
}

In my openIt function in app.js file i am not getting item.name. In my console it displays error that item is not defined. But when i pass static data i.e onclick="openIt('sample_data')"it does not show any error.

Even though item.name also exists i am getting correct values against this as well. I am not getting that why i am not able to pass iterative data to the parameters.

like image 529
Ahmad Habib Avatar asked Jan 01 '23 09:01

Ahmad Habib


1 Answers

If you're using Angular then you should go with (click) because when you declare an event handler you need to surround the DOM event name in parentheses and assign a template statement to it.

<button class="tabopen" (click)="openIt(item.name)">{{item.name}}</button>
like image 89
Mihai Alexandru-Ionut Avatar answered Jan 03 '23 00:01

Mihai Alexandru-Ionut