You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:00:02