Validation on Kendo UI for Angular DatePicker not working

十年热恋 提交于 2020-01-05 05:39:25

问题


I'm trying to use form validation on a Kendo UI for Angular DatePicker and it just doesn't seem to work.

I'm doing the following on all other form elements:

<div class="form-group row" [ngClass]="{ 'has-danger' : email.invalid && (email.dirty || email.touched) }">
    <input id="email" type="text" class="form-control" [(ngModel)]="member.email" name="email" #email="ngModel" required />
</div>

This works perfectly fine.

But when I try the same with the Kendo UI for Angular DatePicker I get the following error:

<div class="form-group row" [ngClass]="{ 'has-danger' : geburtsdatum.invalid && (geburtsdatum.dirty || geburtsdatum.touched) }">
    <kendo-datepicker
      id="geburtsdatum"
      [format]="'dd.MM.yyyy'"
      [(value)]="mitglied.geburtsdatum"
      #geburtsdatum="ngModel"
      required>
    </kendo-datepicker>
</div>

Now I get the error:

There is no directive with "exportAs" set to "ngModel".

I can't seem to find a way to validate Kendo UI for Angular form elements in a simple way.


回答1:


The exportAs defines the name under, which the component/directive will be exported. In this case, you would like to export ngModel, which is not present in the component declaration. The solution is simple - just use [(ngModel)] instead of [(value)] binding. Thus Angular will be able to select NgModel instance and export it:

<kendo-datepicker
  id="geburtsdatum"
  [format]="'dd.MM.yyyy'"
  [(ngModel)]="mitglied.geburtsdatum"
  #geburtsdatum="ngModel"
  required>
</kendo-datepicker>

Check the Angular Form documentation for more details, how to show/hide validation errors properly.

https://angular.io/guide/forms#show-and-hide-validation-error-messages

[TL;DR]

The DatePicker component implements the ControlValueAccessor interface, which makes it a fully compatible Angular form component. The Angular Validation on the other hand works against AbstractControl instances (basically NgModel or FormControl directives).

With this in mind, in order to get validation working, you will need to decorate the component either with [ngModel] or [formControl|formControlName]:

<kendo-datepicker
       name="birthDate"
       [(ngModel)]="user.birthDate"
       [min]="min"
       [max]="max"
></kendo-datepicker>

Here is a working demo that demonstrates this:

https://plnkr.co/edit/seJ4jLg9WziemQtCVuxk?p=preview

For further readings, refer to the Angular Form documentation:

https://angular.io/guide/user-input



来源:https://stackoverflow.com/questions/47527942/validation-on-kendo-ui-for-angular-datepicker-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!