AngularJS Material大量textarea启用md-no-autogrow的性能问题及解决方案咨询
解决方案建议
1. 按需启用自动增长,而非全局控制
不要给所有textarea统一设置md-no-autogrow,只对当前可见/正在编辑的textarea启用自动增长,其他保持禁用。比如结合Angular的焦点监听,当textarea获得焦点时移除md-no-autogrow属性,失去焦点时重新添加。
示例代码:
<textarea [attr.md-no-autogrow]="!isFocused(itemId) ? '' : null" (focus)="setFocus(itemId)" (blur)="removeFocus(itemId)" ></textarea>
组件逻辑里维护一个焦点ID集合,判断当前textarea是否处于焦点状态即可。
2. 优化自动增长的触发逻辑
原函数的性能问题大概率源于频繁计算高度(比如每次输入都触发)。可以修改或重写自动增长逻辑,减少计算频率:
- 给输入事件加防抖,只在输入暂停后执行高度计算;
- 缓存已计算的高度值,避免相同内容重复计算。
3. 替换为轻量级自定义自动增长指令
如果Angular Material自带的自动增长逻辑过重,自己写一个极简指令实现核心功能:
import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[customAutogrow]' }) export class CustomAutogrowDirective { constructor(private el: ElementRef) {} @HostListener('input') onInput() { this.adjustHeight(); } @HostListener('focus') onFocus() { this.adjustHeight(); } private adjustHeight() { const textarea = this.el.nativeElement; textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px'; } }
使用时去掉md-no-autogrow,添加自定义指令:
<textarea customAutogrow></textarea>
4. 虚拟化渲染大量textarea
如果这些textarea是长列表形式,用Angular CDK的CdkVirtualScrollViewport做虚拟化,只渲染当前视口内的textarea,从根本上减少DOM元素数量,提升整体性能。
内容的提问来源于stack exchange,提问作者Snivio
相关产品推荐
相关产品推荐

