关于angular:我的模板无法读取’id’的属性

 2021-04-27 

my template cannot read the property of 'id'

我正在尝试使用模板中的事件(click)= " editUser(eb_user)"更新用户信息。无法读取属性\\'id \\'。

这是我收到的错误:

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)

这是模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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>

这是editUser()方法:

1
2
3
4
5
6
editUser(user: eb_user){
    this.users = [];
    localStorage.removeItem("editUserId");
    localStorage.setItem("editUserId", user.id.toString());
    this.router.navigate(['edit-user']);
  };

我希望点击事件正常运行


更改为(click)="editUser(user),它在let

中使用用户局部变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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>


您需要做的就是传递用户对象并访问ts中的id,或者您也可以直接从html传递id,这是示例

1
2
3
4
5
6
7
8
9
// 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>

在HTML

中仅按如下所示调用更改函数

1
<td><button (click)="editUser(user)" style="margin-left: 20px;"> Edit</button>|      </td>

您需要传递user项而不是eb_user模型


(click)="editUser(eb_user)"中的eb_user是谁?

它应该是(click)="editUser(user)",因为您要使用ngFor中的user变量遍历users

祝你好运!