[英]Cannot read property '0' of undefined angular
我在下面发布了以下代码。 我正在尝试使表格在点击时可编辑,但是我在下面收到以下错误。 有人可以告诉我为什么吗,解决方法是什么。
<tbody>
<tr *ngFor="let Accounts of accounts">
<td >{{Accounts}} </td>
<td (click)="edit(this)"><input value="{{Accounts}}" disabled onblur="disable(this)"></td>
<td (click)="edit(this)"><input value="{{Accounts}}" disabled onblur="disable(this)"></td>
<td (click)="edit(this)"><input value="{{Accounts}}" disabled onblur="disable(this)"></td>
<td (click)="edit(this)"><input value="{{Accounts}}" disab`enter code here`led onblur="disable(this)"></td>
</tr>
</tbody>
打字稿代码为:
public edit(el) {
el.childNodes[0].removeAttribute('disabled');
el.childNodes[0].focus();
window.getSelection().removeAllRanges();
}
public disable(el) {
el.setAttribute('disabled', '' );
}
我得到的错误是:
ERROR TypeError: Cannot read property '0' of undefined
代替(click)="edit(this)"
,请尝试(click)="edit($event)"
(请参阅从$ event对象获取用户输入 )。
在点击处理程序中,您可以通过event.target
访问元素,
public edit(event) {
const el = event.target as HTMLElement;
el.childNodes[0].removeAttribute('disabled');
el.childNodes[0].focus();
window.getSelection().removeAllRanges();
}
public disable(event) {
const el = event.target as HTMLElement;
el.setAttribute('disabled', '' );
}
页面模板引用变量(#var)也可以使用(您的处理程序方法保持不变)。
您可能希望行之间存在冲突,但是Angular会解决此问题-请参阅此问题如何在* ngFor内设置唯一的模板引用变量? (角度)和演示
<tbody>
<tr *ngFor="let Accounts of accounts">
<td >{{Accounts}} </td>
<td #cell1 (click)="edit(cell1)"><input value="{{Accounts}}" disabled onblur="disable(cell1)"></td>
<td #cell2 (click)="edit(cell2)"><input value="{{Accounts}}" disabled onblur="disable(cell2)"></td>
<td #cell3 (click)="edit(cell3)"><input value="{{Accounts}}" disabled onblur="disable(cell3)"></td>
<td #cell4 (click)="edit(cell4)"><input value="{{Accounts}}" disabled onblur="disable(cell4)"></td>
</tr>
</tbody>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.