1

Is there anyway to detect removed character from a text using ngModel in Angular 2 ?

I want something like:

Original text: @Hello World !

Modified text : Hello World !

Console.log

Removed character: '@'

I've found a cool example on Javascript with Jquery by Arie Xiao below:

https://stackoverflow.com/a/17005983/5668956

But I wonder if I can use another thing beside Jquery, as I find that Jquery is pretty hard to implement in Angular 2

Community
  • 1
  • 1
ThangLeQuoc
  • 2,272
  • 2
  • 19
  • 30

1 Answers1

0

I would suggest a Forms controller for acting on changes on the input field. The snippet displays the character add or deleted from the input field. Check out my Plunker to see the code running.

@Component({
  selector: 'app-root',
  template: `
    <input type="text" [formControl]="form"  class="form-control" >
    <h3 *ngIf="initial">
      Text <span [style.color]="textadd ? 'green' : 'red'" > {{textadd ? "add" : "removed" }} </span>: {{change}}
    </h3>
  `,
})
export class App {
  form;
  textadd;
  text = "@Hello World!";
  initial = false;
  change;
  ngOnInit() {
    this.form = new FormControl({ value: this.text, disabled: false });

    this.form.valueChanges.subscribe(val => {
      let change;
      if (val.length > this.text.length) {
        change = val;
        for (let variable of this.text) {
          change = change.replace(variable, '');
          this.textadd = true;
        }
      } else {
        change = this.text;
        for (let variable of val) {
          change = change.replace(variable, '');
          this.textadd = false;
        }
      }
      this.change = change;
      this.text = val;
      this.initial = true;
    });
  }
}
jervtub
  • 347
  • 1
  • 10