How can I add ngModel custom validator and detect changes in template driven form

31 views Asked by At

I have a lot of ngModels attached to dataType property. For example the dataType looks like this

dataType = {
   filter: true,
   unique: true,
   name:'Some test name'
}

so in the HTML I have something like

 <input
 class="custom-control-input toggle-switcher"
 type="checkbox"
 [(ngModel)]="dataType.data.filter"
 id="filter"
 name="filter"                                   
/>

 <input
 class="custom-control-input toggle-switcher"
 type="checkbox"
 [(ngModel)]="dataType.data.unique"
 id="filter"
 name="filter"                                   
/>

<input type="text" [(ngModel)]="dataType.data.name"/>

on the web page I need to display save button only if there are some changes in the form. So the user loads the page he sees for example three inputs (note: I have a lot more than them). By changes I mean when the user comes to the page he sees text in the type="text" input Some test name. If the user types something in the input for example Some test name 1 because he added 1 the save button should appear. Afterwards when the user for example revert his change - if he removes the 1 then the current state of the UI is the same as the original one - when the user loaded the page so the save button should be removed.

The problem I am facing is that I don't know how can I apply this on ngModel and that to work dynamically. Only solution that came to my mind is having (ngModelChange) on each input and then inside the function for that ngModel. And inside that function to compare the previous state of the dataType and the new state. The problem with that is that on component where I have for example 15 models I will have 15 functions on ngModelChange. So is there any better way where with applying custom validator I can detect changes on the template driven form.

HTML

<input type="text" [(ngModel)]="dataType.data.name" (ngModelChange)="onNameChange()"/>
<input
 class="custom-control-input toggle-switcher"
 type="checkbox"
 [(ngModel)]="dataType.data.unique"
 (ngModelChange)="onFilterChange()"
 id="filter"
 name="filter"                                   
/>

TS

dataType = {
   filter: true,
   unique: true,
   name:'Some test name'
}
this.copiedDataType = clone(dataType);
onNameChange() {
  // now here I have access to the changes of the dataType and I have original name in the copiedDataType
  if(this.dataType.name !== this.copiedDataType.name) {
     // that means that there was change on the NAME MODEL
  }
}

// THE SAME WILL BE FOR ALL OTHER INPUTS...

I forgot to mention that I need to use template driven forms instead of reactive driven forms. I know that with reactive driven forms there is valueChanges observable where I can subscribe to it and get all of the changes.

0

There are 0 answers