Reputation: 139
I am trying to call a function whenever i click a row in an HTML table but it is not working and it is not giving any errors.
I've tried several things, and online code shows that the way i try it, it should be working.
My code is as following:
Html:
<h2>Userstories</h2>
<button (click)="onNewStory()">New Story</button>
<table>
<tr *ngFor="let story of userstories" ng-click="onUpdate(story)" [class.selected]="story === selectedStory">
<td>{{story.id}}</td>
<td>{{story.name}}</td>
<td><button ng-click="onUpdate(story)">Click me!</button></td>
</tr>
</table>
<app-userstory-detail [story]="selectedStory"></app-userstory-detail>
And my .ts looks like this:
selectedStory: UserStory;
onNewStory() {
var newStory = {id:this.userstories[this.userstories.length-1].id+1, name:"", description:"Deze is nieuw", status:"open", owner:USERS[1]};
this.userstories.push(newStory);
this.selectedStory = newStory;
}
onUpdate(userstory: UserStory): void {
this.selectedStory = userstory;
console.log(this.selectedStory);
}
Currently my console is not printing the log, when i try to call the onUpdate method. The expected result is to see some output in the logs, but i have no clue why it is not firing the onUpdate method.
Upvotes: 5
Views: 21348
Reputation: 1442
The event is fired twice. In <tr>
and in <button>
.
Try this:
<h2>Userstories</h2>
<button (click)="onNewStory()">New Story</button>
<table>
<tr *ngFor="let story of userstories" [class.selected]="story === selectedStory">
<td>{{story.id}}</td>
<td>{{story.name}}</td>
<td><button (click)="onUpdate(story)">Click me!</button></td>
</tr>
</table>
<app-userstory-detail [story]="selectedStory"></app-userstory-detail>
Upvotes: 1
Reputation: 1395
ng-click
is actually for AngularJS (1.x)
You want to use (click)
which is for Angular.
DOCUMENTATION: https://angular.io/guide/ajs-quick-reference#ng-click
Upvotes: 1
Reputation: 10697
In angular 7 you can use (click)
which is similar to ng-click
of Angular JS.
Try:
<h2>Userstories</h2>
<button (click)="onNewStory()">New Story</button>
<table>
<tr *ngFor="let story of userstories" (click)="onUpdate(story)" [class.selected]="story === selectedStory">
<td>{{story.id}}</td>
<td>{{story.name}}</td>
<td><button (click)="onUpdate(story)">Click me!</button></td>
</tr>
</table>
<app-userstory-detail [story]="selectedStory"></app-userstory-detail>
Upvotes: 8