Angular中如何从ngFor渲染的HTML传递选中项titulo到TS组件
解决Angular点击链接传递选中项titulo的问题
不需要用双向绑定,直接在点击事件里传递当前项的titulo即可,以下是具体实现:
1. 组件TS代码
先确保已通过showNodes()获取数据数组,新增一个接收选中titulo的方法:
import { Component } from '@angular/core'; import { BuscadorService } from './buscador.service'; // 替换成你的服务实际路径 @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent { dataArray: any[] = []; constructor(private buscadorService: BuscadorService) {} showNodes() { // 假设服务返回Observable,订阅获取数据数组 this.buscadorService.getNodes().subscribe((response) => { this.dataArray = response; }); } // 接收选中的titulo并打印 onTituloSelected(titulo: string) { console.log('选中的标题:', titulo); } }
2. HTML模板代码
在ngFor循环的链接上绑定点击事件,直接传递当前项的info.titulo:
<div *ngFor="let info of dataArray"> <!-- 用$event.preventDefault()阻止a标签默认跳转行为 --> <a href="#" (click)="onTituloSelected(info.titulo); $event.preventDefault()"> {{ info.resolucion }} | {{ info.ano }} | {{ info.titulo }} </a> </div>
说明
- 点击链接时,当前循环项的
titulo会作为参数传入onTituloSelected方法,直接在TS中处理即可。 - 如果不需要跳转行为,必须加上
$event.preventDefault(),或者改用<button>标签并设置成链接样式。
内容的提问来源于stack exchange,提问作者HomerO
相关产品推荐
相关产品推荐

