具有自定义验证的Angular5模板驱动表单不会重置验证错误

时间:2018-05-18 14:23:55

标签: angular5 custom-validators

I am using angular5 forms with custom validation.

但是在表单重置验证错误不会重置。     我正在使用此验证器来检查文本字段中的空格。

我们如何使用角度5中的模板驱动表单的验证状态重置控件?我知道可以通过设置绑定到的模型值来重置控件

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 个答案:

没有答案