0

I am using an text input field in my angular code and I want to check if it is dirty or not:

<input 
      *ngIf="!formated" 
      class="textinput-group__textinput" 
      id="{{name}}" 
      [type]="type" 
      [(ngModel)]="inputModel"
      (ngModelChange)="inputModelChange.emit(inputModel)"
      [maxlength]='maxLength'
      (input)="onValueChange($event)" 
      [ngClass]="{'disabled': isDisabled, 'error': isErrored}"
      [disabled]="isDisabled ? isDisabled : null" 
      (focus)="onFocus()" 
      (blur)="onBlur()"
      [ngStyle]="textStyle">

The $event property passed to the OnValueChange() doesn't contain the dirty property:

onValueChange(event: any): void {
    console.log("event:" + event);
    this.onChange.emit(event.target.value);
  }

How else can I get it?

The Inquisitive Coder
  • 1,085
  • 3
  • 20
  • 43

2 Answers2

2

Using template reference variable we can set ngModel on input element, The we can pass template references to onValueChange method to check whether input is dirty or not.

component.html

 <input 
          *ngIf="!formated" 
          class="textinput-group__textinput" 
          id="{{name}}" 
          [type]="type" 
          [(ngModel)]="inputModel"
          #ref="ngModel"
          (ngModelChange)="inputModelChange.emit(inputModel)"
          [maxlength]='maxLength'
          (input)="onValueChange($event,ref)" 
          [ngClass]="{'disabled': isDisabled, 'error': isErrored}"
          [disabled]="isDisabled ? isDisabled : null" 
          (focus)="onFocus()" 
          (blur)="onBlur()"
          [ngStyle]="textStyle">

component.ts

onValueChange(event: any,ref:NgModel): void {
    console.log("event:" + event);
    this.onChange.emit(ref.dirty);
  }
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
0

It can be done with reactive form control. ngModel gives you two way binding, not anything else.

HTML

<input *ngIf="!formated" 
       class="textinput-group__textinput" 
       id="{{name}}" 
       [type]="type" 
       [formControl]="control"
       [maxlength]='maxLength'
       [ngClass]="{'disabled': isDisabled, 'error': isErrored}"
       [disabled]="isDisabled ? isDisabled : null" 
       (focus)="onFocus()" 
       (blur)="onBlur()"
       [ngStyle]="textStyle">

TS

    control = new FormControl();


    // where you want to catch the events
    this.control.valuechanges.subscribe(value => {
    // your code
    })