user14801702
user14801702

Reputation:

*ngFor in a button is not working in Angular

I have a datatable with a button at each row. This button works

<button mat-raised-button color="primary" (click)="action(car.id)">Action</button>

I'm trying to create a button that call action(car.id) for all the rows of the datatable, so for all the car.id

<button>
    <div *ngFor='let cars of car'>
      <span (click)='this.action(cars.id)'>Action</span>
    </div>
</button>

The button returns just ONE od the ids I tried to modify it by changing the location of the *ngFor but it stills not working. If I put the *ngFor in the button tag, it creates multiple buttons that works, but I just need one button to click on it

Upvotes: 0

Views: 1359

Answers (2)

agofelix
agofelix

Reputation: 1

your ts should be like this for use binding in * ngFor

 action(x:any){

  console.log(x)
  return this.cars
 }

then you can:

<div *ngFor="let car of cars">
<button mat-raised-button color="primary" (click)="action(car.id)">Action</button>
</div>

Upvotes: 0

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18909

Inside your component ts file

public actionForAll(){
  this.cars.forEach((car) => {
     this.action(car.id)
   });
}

Inside your component html file

<button mat-raised-button color="primary" (click)="actionForAll()">Action</button>

Upvotes: 1

Related Questions