2
I am using angular5 forms with custom validation.

But on form reset validation errors does not resets. I am using this validator for checking white spaces in the textfield.

How do we reset the controls with validation states of Template driven forms in angular 5? I know that controls can be reset by setting model values to which they are bound to

RequiredFieldDirective.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';

@Directive({
  selector: '[requiredField][ngModel]',
  providers: [{
                provide: NG_VALIDATORS,
                useExisting: RequiredFieldDirective,
                multi: true
            }]
})
export class RequiredFieldDirective implements Validator {

  validate(c: AbstractControl): {[key: string]: any} {
        console.log(c.value)
        if(c.value){
            let v = c.value.toString().trim();
            return ( v == '')? {"requiredField": true} : null;
        }
  }
}

html
<input class="{{dashboardNameInput1.invalid && dashboardNameInput1.pristine && isFormInValid?'text-field-dashboard-inValidInput':'text-field-dashboard'}}"
             name="dashboardName"
             autocomplete="false"
             type="text" i18n-placeholder placeholder="Dashboard Name"
             [ngModel]="dashboard?.dashboardName"
             maxlength="255"
             required
             requiredField
             #dashboardNameInput1="ngModel"
      />
      <br>
      <span class="errorMessageDashboard" i18n  *ngIf="dashboardNameInput1.errors?.requiredField">
              Please Enter Dashboard Name.
      </span>
      <span class="errorMessageDashboard" [hidden]="dashboardNameInput1.valid || (dashboardNameInput1.pristine && !controlVariable?.dashboardName?.invalid)">
          <span i18n  *ngIf="dashboardNameInput1.errors?.required">
              Please Enter Dashboard Name.
          </span>
      </span>
<button *ngIf="!editModeDashboardName" class="button-style-08" (click)="createNewDashboard(dashboardForm)" i18n>Add</button>

ts
@ViewChild('dashboardForm') dashboardForm;

updateDashboardName(dashboardForm){


  this.dashboardForm.reset()
this.dashboardForm.resetForm()
dashboardForm.reset();
            dashboardForm.resetForm();
    }

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.