Angular 13 Kendo UI:如何读取文本框已删除内容并同步移除
实现方案
核心思路
监听Kendo TextArea的valueChange事件,对比每次值变化前后的内容,定位被删除的片段,再同步从第二个文本框中移除对应内容。
具体实现步骤
1. 模板结构
在组件HTML中添加两个Kendo文本框,绑定数据模型并给源文本框绑定值变更事件:
<kendo-textarea [(ngModel)]="sourceText" (valueChange)="handleSourceChange($event)" placeholder="输入/删除内容"> </kendo-textarea> <kendo-textarea [(ngModel)]="targetText" placeholder="同步移除删除内容"> </kendo-textarea>
2. 组件逻辑处理
在TS文件中实现值对比和内容同步逻辑:
import { Component } from '@angular/core'; @Component({ selector: 'app-text-sync', templateUrl: './text-sync.component.html' }) export class TextSyncComponent { sourceText = ''; targetText = ''; private lastSourceValue = ''; handleSourceChange(newVal: string): void { // 找出被删除的内容片段 const deletedPart = this.getDeletedContent(this.lastSourceValue, newVal); if (deletedPart) { // 从目标文本中移除对应内容 this.targetText = this.targetText.replace(deletedPart, ''); // 如需替换所有重复匹配,改用正则:this.targetText.replace(new RegExp(deletedPart, 'g'), '') } // 更新上一次的源文本记录 this.lastSourceValue = newVal; } private getDeletedContent(oldVal: string, newVal: string): string | null { // 只有旧值长度大于新值时,才存在删除操作 if (oldVal.length <= newVal.length) return null; // 从头部开始找第一个不同的位置 let startPos = 0; while (startPos < newVal.length && oldVal[startPos] === newVal[startPos]) { startPos++; } // 从尾部向前找最后一个不同的位置 let endPos = oldVal.length - 1; let newEndPos = newVal.length - 1; while (endPos >= startPos && newEndPos >= startPos && oldVal[endPos] === newVal[newEndPos]) { endPos--; newEndPos--; } // 返回被删除的连续片段 return oldVal.substring(startPos, endPos + 1); } }
3. 额外注意事项
- 确保已在模块中引入Kendo的TextArea模块:
import { TextAreaModule } from '@progress/kendo-angular-inputs'; @NgModule({ imports: [TextAreaModule] }) export class YourFeatureModule { }
- 如果要处理非连续删除、复杂文本替换等场景,可以替换
getDeletedContent方法为更精细的文本差异算法(比如基于Levenshtein距离的对比),但上述简单对比足以覆盖大多数日常场景。
内容的提问来源于stack exchange,提问作者Raghu Ch
相关产品推荐
相关产品推荐

