Angular中点击HTML列表元素时如何将数据库对应品牌ID赋值给变量
Angular 品牌列表点击绑定ID实现方法
实现前提
首先确认你获取到的brands数组每一项都已经正确返回了数据库存储的id字段值,之后可按照以下两种方案按需实现:
方案一:直接在模板内赋值(适合不需要额外逻辑的场景)
直接在<li>标签上绑定Angular点击事件(click),点击时直接给brand_id赋值,修改后的模板代码如下:
<ul class="d-flex list-unstyled justify-content-around w-50 mx-auto mt-5"> <li *ngFor="let brand of brands" (click)="brand_id = brand.id"> {{ brand.name }} </li> </ul>
方案二:绑定TS方法(适合需要额外处理逻辑的场景)
- 先修改模板代码,点击时调用自定义方法,将当前品牌的id作为参数传入:
<ul class="d-flex list-unstyled justify-content-around w-50 mx-auto mt-5"> <li *ngFor="let brand of brands" (click)="onBrandSelect(brand.id)"> {{ brand.name }} </li> </ul>
- 在对应的TypeScript文件中添加对应处理方法:
// 你已定义的存储选中品牌ID的变量 brand_id: number | null = null; // 选中品牌时触发的处理方法 onBrandSelect(selectedId: number): void { this.brand_id = selectedId; // 此处可添加后续业务逻辑,比如触发对应品牌的商品查询、缓存选中值等 }
可选优化:可以增加选中状态样式绑定,方便用户识别当前选中项,示例如下:
<li *ngFor="let brand of brands" (click)="onBrandSelect(brand.id)" [class.selected]="brand.id === brand_id" > {{ brand.name }} </li>之后在对应CSS文件中添加
.selected类的样式即可,比如修改字体颜色、增加选中边框等。
内容的提问来源于stack exchange,提问作者Osama Amr
相关产品推荐
相关产品推荐

