Validation on Kendo UI for Angular DatePicker not

2019-07-29 06:37发布

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条回答
放荡不羁爱自由
2楼-- · 2019-07-29 07:11

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

查看更多
登录 后发表回答