Usando google-diff-match-patch en angular

Aug 25 2020

Me gustaría usar el google diff/match/patch liben una aplicación angular para mostrar la diferencia entre dos textos.

Mi uso sería algo como esto:

public ContentHtml: SafeHtml;
compare(text1: string, text2: string):void {
        var dmp = new diff_match_patch();

        dmp.Diff_Timeout = 1;
        dmp.Diff_EditCost = 4;

        var d = dmp.diff_main(text1, text2);
        dmp.diff_cleanupSemantic(d);
        var ds = dmp.diff_prettyHtml(d);

        this.ContentHtml = this._sanitizer.bypassSecurityTrustHtml(ds);
}

El problema es, ¿cómo puedo importar diff_match_patchpara esta línea?
var dmp = new diff_match_patch();

Respuestas

1 ShashankVivek Aug 25 2020 at 13:02

Debe importar el paquete npm para el proyecto angular en formato package.json.

"diff-match-patch": "^1.0.5",

e importar en componente como:

import { Component } from '@angular/core';
import DiffMatchPatch from 'diff-match-patch';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  getDiff() {
    var dmp = new DiffMatchPatch();
    var diff = dmp.diff_main('Hello', 'Hallo');
    // Result: [(-1, "Hell"), (1, "G"), (0, "o"), (1, "odbye"), (0, " World.")]
    dmp.diff_cleanupSemantic(diff);
    // Result: [(-1, "Hello"), (1, "Goodbye"), (0, " World.")]
    console.log(diff);
  }

}

Aquí hay un código de demostración