Angular中如何保存ngFor点击元素值并在另一组件使用
解决方案
针对你的需求,有几种常用的方法可以保存点击的t值并在其他组件中使用,下面结合你的代码给出具体实现:
方法一:通过MatDialog关闭回调传值(最直接)
因为你用的是Material Dialog,直接利用它的关闭回调就能获取选中的值,再通过路由传参传给目标组件:
1. 修改弹窗组件模板
将mat-dialog-close绑定为当前t值,点击时自动把值带回:
<div class="popup-content"> <ul class="list-group"> <li [mat-dialog-close]="t" routerLink='/admin' *ngFor="let t of data" class="list-group-item"> {{t}} </li> </ul> </div>
2. 在弹窗调用组件中接收值并路由传参
修改openDialog方法,订阅弹窗关闭事件拿到选中值,再通过路由参数传给/admin组件:
import { Router } from '@angular/router'; // 构造函数注入Router constructor(private dialog: MatDialog, private router: Router) {} openDialog(){ const dialogRef = this.dialog.open(MenupopupComponent,{data:this.test}); dialogRef.afterClosed().subscribe(selectedUuid => { if(selectedUuid){ // 跳转到admin组件并携带参数 this.router.navigate(['/admin'], { queryParams: { uuid: selectedUuid } }); } }); }
3. 在Admin组件中获取参数
注入ActivatedRoute来获取路由参数:
import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) {} ngOnInit(){ this.route.queryParams.subscribe(params => { const selectedUuid = params['uuid']; if(selectedUuid){ // 这里就可以使用选中的t值结合API操作 console.log('选中的UUID:', selectedUuid); // 例如调用API: this.apiService.doSomething(selectedUuid) } }); }
方法二:通过共享服务传递值(适合跨多个组件共享)
创建一个全局服务来保存选中的值,任何组件都可以订阅获取:
1. 创建共享服务
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataShareService { private selectedUuid$ = new BehaviorSubject<string | null>(null); setSelectedUuid(uuid: string): void { this.selectedUuid$.next(uuid); } getSelectedUuid(): Observable<string | null> { return this.selectedUuid$.asObservable(); } }
2. 弹窗组件中设置值
修改弹窗模板添加点击事件,调用服务保存值:
<div class="popup-content"> <ul class="list-group"> <li (click)="onSelect(t)" mat-dialog-close routerLink='/admin' *ngFor="let t of data" class="list-group-item"> {{t}} </li> </ul> </div>
弹窗组件TS代码:
import { DataShareService } from '../path/to/data-share.service'; constructor(private dataShareService: DataShareService) {} onSelect(uuid: string): void { this.dataShareService.setSelectedUuid(uuid); }
3. Admin组件中获取值
订阅服务中的值:
import { DataShareService } from '../path/to/data-share.service'; constructor(private dataShareService: DataShareService) {} ngOnInit(){ this.dataShareService.getSelectedUuid().subscribe(uuid => { if(uuid){ // 使用选中的UUID操作API console.log('选中的UUID:', uuid); } }); }
额外提示
你原来代码中console.log(this.test)写在subscribe外面,会打印空数组,因为HTTP请求是异步的,要把打印逻辑放到subscribe回调里:
this.service.getPosts() .subscribe(response => { this.posts = response; this.num = this.posts.body.paginationinfo.numberofelementsTotal; for(this.i=0;this.i<this.num;this.i++){ this.test.push(this.posts.body.listOfUnapprovedChangeRequests[this.i].requestuuid); } console.log(this.test); // 移到这里才能打印到数据 });
内容的提问来源于stack exchange,提问作者user19938599
相关产品推荐
相关产品推荐

