Reputation: 75
I'm trying to update a user's information using the event (click) = "editUser (eb_user)" in the template. The attribute 'id' is not read.
Here is the error I receive:
ERROR TypeError: Cannot read property 'id' of undefined at UsersComponent.push../src/app/component/users/users.component.ts.UsersComponent.editUser (users.component.ts:32) at Object.eval [as handleEvent] (UsersComponent.html:24) at handleEvent (core.js:23107) at callWithDebugContext (core.js:24177) at Object.debugHandleEvent [as handleEvent] (core.js:23904) at dispatchEvent (core.js:20556) at core.js:21003 at HTMLButtonElement. (platform-browser.js:993) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423) at Object.onInvokeTask (core.js:17290)
This is the template:
<table class="table table-striped; mat-elevation-z8" style="width: 100%;">
<tr>
<th>#</th>
<th>Nom</th>
<th>Prénom</th>
<th>Action</th>
</tr>
<tr *ngFor = "let user of users">
<td>{{user.id}}</td>
<td>{{user.nom}}</td>
<td>{{user.prenom}}</td>
<td><button class="btn btn-primary" (click)="editUser(eb_user)" style="margin-left: 20px;"> Edit</button>|
</td>
</tr>
Here is the editUser () method:
editUser(user: eb_user){
this.users = [];
localStorage.removeItem("editUserId");
localStorage.setItem("editUserId", user.id.toString());
this.router.navigate(['edit-user']);
};
I expect the click event normally works
Upvotes: 1
Views: 632
Reputation: 1171
Just change function calling like follows in Html
<td><button (click)="editUser(user)" style="margin-left: 20px;"> Edit</button>| </td>
You need to pass user
item not eb_user
Model
Upvotes: 0
Reputation: 2327
All you need to do is pass the user object and access the id in ts or you can also pass the id directly from html here is an example
// here we are passing user object
<tr *ngFor = "let user of users">
<td><button class="btn btn-primary" (click)="editUser(user)" style="margin-left: 20px;"> Edit</button></td>
</tr>
// here we are passing user.id to ts
<tr *ngFor = "let user of users">
<td><button class="btn btn-primary" (click)="editUser(user.id)" style="margin-left: 20px;"> Edit</button></td>
</tr>
Upvotes: 0
Reputation: 1889
Who is eb_user
from (click)="editUser(eb_user)"
?
It should be (click)="editUser(user)"
because you do iterate over users
with user
variable in ngFor.
Good luck!
Upvotes: 0
Reputation: 18975
Change to (click)="editUser(user)
it use user local variable in let
<table class="table table-striped; mat-elevation-z8" style="width: 100%;">
<tr>
<th>#</th>
<th>Nom</th>
<th>Prénom</th>
<th>Action</th>
</tr>
<tr *ngFor = "let user of users">
<td>{{user.id}}</td>
<td>{{user.nom}}</td>
<td>{{user.prenom}}</td>
<td><button class="btn btn-primary" (click)="editUser(user)" style="margin-left: 20px;"> Edit</button>|
</td>
</tr>
Upvotes: 0