Angular 8:函数调用传JSON元素ID报错,如何解决并实现迭代?
解决Angular点击事件传参报错问题
你的问题出在Angular模板语法使用错误——事件绑定的表达式内部不需要用插值语法{{}},直接引用变量即可。
修正后的按钮代码
<button (click)="getData(forecast.id)">Test</button>
注意:按钮标签与(click)属性之间需要加空格,避免语法解析异常。
原因说明
在Angular的事件绑定(如(click))上下文里,本身就支持直接使用模板变量(比如循环中的forecast),不需要额外用{{}}包裹。如果强行加插值语法,Angular会将其识别为字符串拼接,而非合法的表达式变量,从而触发语法错误。
循环场景的完整示例
如果你需要遍历多个ID生成按钮,用*ngFor结合修正后的点击事件即可:
<!-- 模板文件 --> <div *ngFor="let forecast of forecasts"> <button (click)="getData(forecast.id)">测试ID: {{ forecast.id }}</button> </div> <div id="idMod">{{ currentId }}</div>
// component.ts 文件 import { Component } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { forecasts = [ { id: 1 }, { id: 2 }, { id: 3 } ]; currentId: string; getData(id: number) { this.currentId = id.toString(); console.log(this.currentId); } }
这里建议用Angular的数据绑定替代直接操作DOM(比如document.getElementById),更符合框架的最佳实践。
内容的提问来源于stack exchange,提问作者user19761134
相关产品推荐
相关产品推荐

