Home > Software engineering >  How to make an input field revert to "pristine/untouched" once filled in Angular?
How to make an input field revert to "pristine/untouched" once filled in Angular?

Time:11-03

I have an input in a modal box and I want to revert it back to pristine once I click the "ok" button. I'm making some sort of to do list in which everytime I fill an input and click the "ok" button the value I've written gets saved in a list.

The problem is that I want to keep the "ok" button disabled everytime the input "refreshes" thanks to (click)="task.value = ''" and that only works at the start when the page gets refreshed.

Once I type anything it becomes "dirty" and "touched", i assume I'm supposed to make it stay "pristine/untouched"?

HTML:

<div class="modal">
    <p>What did you do?</p>

    <input type="text" [(ngModel)]="activity.name" #task />
    <button
      (click)="addTask(task.value)"
      (click)="task.value = ''"
      [disabled]="activity.name === ''"
    >
      OK
    </button>
  </div>

TS:

activity: Activity = {
    name: '',
  };
  addTask(item: string) {
    this.list.push({ name: item });
  }

CodePudding user response:

Well this is not a form, so it cannot be made pristine or untouched.

Your button is currently disabled when activity.name is an empty string, after you press the button you set task.value to an empty string. That is not the same thing as your object activity. If you want to achieve the same, you need to actually set the activity.name to an empty string for your condition to be fulfilled. As we are using two-way-binding you can also do this in your addTask function. I would just do:

template:

<input type="text" [(ngModel)]="activity.name" />
<button (click)="addTask()" [disabled]="!activity.name">OK</button>

TS:

addTask() {
  this.list.push({ name: this.activity.name });
  this.activity.name = '';
}
  • Related