Angular中更新MatTableDataSource后焦点消失的解决办法求助
解决方案
核心问题分析
你每次在ngOnChanges里新建MatTableDataSource实例,会触发表格DOM完全重渲染,之前聚焦的输入框被销毁重建,导致焦点丢失。
方案一:复用MatTableDataSource实例(推荐)
初始化时创建一次数据源,后续仅更新其data属性,避免DOM重渲染:
// 组件初始化阶段创建数据源实例 ngOnInit(): void { this.dataSource = new MatTableDataSource<ArticleDef & Selectable>([]); } ngOnChanges(changes: SimpleChanges): void { if (changes.articles) { // 直接更新data属性,而非新建数据源实例 this.dataSource.data = changes.articles.currentValue; } }
方案二:记录并恢复焦点(适用于必须重建数据源的场景)
如果业务逻辑要求必须重建数据源,可在更新前记录当前焦点元素的标识,更新后重新定位聚焦:
private focusedArticleId: string | null = null; focusedIn(event: Event, article: ArticleDef): void { this.activeArticle = article; this.facade.active(article.id); this.focusedArticleId = article.id; // 记录当前聚焦的文章ID } ngOnChanges(changes: SimpleChanges): void { if (changes.articles) { this.dataSource = new MatTableDataSource<ArticleDef & Selectable>(changes.articles.currentValue); // 数据源更新后异步恢复焦点 setTimeout(() => { if (this.focusedArticleId) { const inputElement = document.querySelector(`input[data-article-id="${this.focusedArticleId}"]`) as HTMLInputElement; inputElement?.focus(); } }); } }
同时需要在模板的输入框上添加自定义属性用于定位:
<input (focus)="focusedIn($event, article)" (change)="changeQuantity($event, article)" [attr.data-article-id]="article.id" >
补充优化点
- 把
changeQuantity的(change)事件换成(input),可以实时响应输入,减少不必要的数据源更新时机 - 配合
trackBy函数优化表格渲染性能,避免无意义的行重渲染:
<table mat-table [dataSource]="dataSource" [trackBy]="trackByArticleId"> <!-- 列定义 --> </table>
trackByArticleId(index: number, item: ArticleDef & Selectable): string { return item.id; }
内容的提问来源于stack exchange,提问作者jesper
相关产品推荐
相关产品推荐

