- 安装google的
diff-match-patch-ts
插件
npm i diff-match-patch-ts
- 添加文本对比管道
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;
}
}
- html页面使用, 配合
[innerHTML]
指令使用效果更佳
<div [innerHTML]="newText|compareStr:oldText"></div>
-
效果示例
文本对比示例.png
PS: 如果我的文章帮到了你, 免费的赞走一个呗~
网友评论