Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using google-diff-match-patch in angular

I'd like to use the google diff/match/patch lib in an angular app to show the difference between two texts.

My usage would be something like this:

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);
}

Problem is, how do I import diff_match_patch for this line?
var dmp = new diff_match_patch();

like image 388
Sam Avatar asked Oct 27 '25 17:10

Sam


1 Answers

You need to import the npm package for angular project in package.json.

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

and import in component as:

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);
  }

}

Here is a demo code

like image 160
Shashank Vivek Avatar answered Oct 30 '25 08:10

Shashank Vivek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!