Home > Net >  Angular custom directive for fromdate todate validator not loading
Angular custom directive for fromdate todate validator not loading

Time:12-14

I need to validate two date fields. Therefore I used custom directive to do it. But My directive not loading and giving error.

this is my custom directive

directive

    import {AbstractControl, NG_VALIDATORS, Validator} from '@angular/forms';
    import {Directive, Input} from '@angular/core';
    @Directive({
        selector:'isLessThanStartDate',
        providers: [{provide:NG_VALIDATORS, useExisting:'EndDateValidatorDirective', multi:true}]
    })
    export class EndDateValidatorDirective implements Validator{
        @Input('isLessThanStartDate') shouldbeless:any;
        validate(control: AbstractControl):{[key:string]:any} | null
        {
            const sDate = new Date(this.shouldbeless);
            const eDate = new Date (control.value);
            console.log(this.shouldbeless);
            console.log(control.value);
            console.log((sDate > eDate) ? {'StartDateIsMore':true}:null);
    
            return (sDate > eDate) ? {'StartDateIsMore':true}:null
        }
    }

this is my date pickers

      <input  placeholder="yyyy-mm-dd"
                                                name="fromdatesearch" [readonly]="true" #fd="ngModel"   
                                                [(ngModel)]="holidaysearch.fromdatesearch" ngbDatepicker
                                                #d1="ngbDatepicker"   (dateSelect)="selectedFromDate(holidaysearch.fromdatesearch)" [maxDate]="maxDate">


      <input  isLessThanStartDate="{{fd.value}}" placeholder="yyyy-mm-dd" [minDate]="minDate" 
                                                name="todatesearch" [readonly]="true" #td="ngModel" (dateSelect)="selectedToDate(holidaysearch.todatesearch)"
                                                [(ngModel)]="holidaysearch.todatesearch" ngbDatepicker
                                                #d2="ngbDatepicker"  >

I imported my custom directive in the app.module. enter image description here

I am using this directive inside the Holiday component. But i did not attached directive in the holiday module. imported only the app module.

This is the error

enter image description here

I need to use custom directive inside the holiday component. how i correctly do it

CodePudding user response:

attribute slectors need to marked in selector with brackets [], now it's not recognized as a directive, so Angular correctly tells you that no such attribute exists on an input field.

So change your selector to:

selector:'[isLessThanStartDate]',
  • Related