美文网首页
angular 文本对比实现 diff-match-patch

angular 文本对比实现 diff-match-patch

作者: 饱饱想要灵感 | 来源:发表于2022-12-14 21:38 被阅读0次
  1. 安装google的diff-match-patch-ts插件
npm i diff-match-patch-ts
  1. 添加文本对比管道
import {Pipe, PipeTransform} from "@angular/core";

import {DiffMatchPatch} from 'diff-match-patch-ts';
import {DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'compareStr' })
export class CompareStrPipeline implements PipeTransform {

    diffMatchPatch = new DiffMatchPatch();

    constructor(private sanitized: DomSanitizer) { }
    
    transform(value, oldValue) {
        if (!value) {
            value = '';
        }
        if (!oldValue) {
            oldValue = value;
        }
        return this.sanitized.bypassSecurityTrustHtml(this.whatIsDiff(oldValue, value));
    }

    whatIsDiff(text1, text2):string {
        const diff = this.diffMatchPatch.diff_main(text1, text2);
        let diffStr = '';
        diff.forEach(item => {
            if (item[0] == 0) {
                diffStr += item[1];
            }
            if (item[0] == -1) {
                diffStr += '<label style="padding:2px 0; text-decoration: line-through;background-color:#F7C9CE;">' +  item[1] + '</label>';
            }
            if (item[0] == 1) {
                diffStr += '<label style="padding:2px 0; background-color:#67db7d;">' +  item[1] + '</label>';
            }
        });
        return diffStr;
    }
}
  1. html页面使用, 配合[innerHTML]指令使用效果更佳
<div [innerHTML]="newText|compareStr:oldText"></div>
  1. 效果示例


    文本对比示例.png

PS: 如果我的文章帮到了你, 免费的赞走一个呗~

相关文章

网友评论

      本文标题:angular 文本对比实现 diff-match-patch

      本文链接:https://www.haomeiwen.com/subject/olmlqdtx.html