Search code examples
angularangular-directivevmware-clarity

Can't send input parameter to validator directive in Angular


I have a simple clarity input in my project (StackBlitz ref is here).

<div class="clr-form-control" [ngClass]="{'clr-error': myInput.errors}">
    <label class="clr-control-label">My Input</label>
    <div class="clr-control-container">
        <div class="clr-input-wrapper">

            <input id="myinput" type="number" class="clr-input" min="1" max="10"
                [(ngModel)]="inputValue" #myInput="ngModel" appMyCheck="12"/>

            <clr-icon class="clr-validate-icon" shape="exclamation-circle"></clr-icon>
        </div>
        <span class="clr-subtext" *ngIf="myInput.errors?.inRange">
            Error
          </span>
    </div>
</div>

I added a validator directive appMyCheck to it. Here is the directive's code

@Directive({
  selector: '[appMyCheck]',
  providers: [{provide: NG_VALIDATORS, useClass: MyCheckDirective, multi: true}]
})
export class MyCheckDirective implements Validator {
  @Input('appMyCheck') myValue;
  constructor() { }

  validate(control: AbstractControl): {[key: string]: any} | null {
    console.log('in validate ', this.myValue);
    return null;
  }
}

So I try to send a parameter myValue (which is sent from template code appMyCheck="12") into the directive and just print it. But it always displays undefined value.

in validate  undefined
in validate  undefined

How can I send a parameter to the validator directive correctly ?


Solution

  • I edit your code and it work https://stackblitz.com/edit/clarity-nkksjf?file=app%2Fmy-check.directive.ts

    import {Directive, Input, forwardRef} from '@angular/core';
    import {AbstractControl, NG_VALIDATORS, Validator} from "@angular/forms";
    
    @Directive({
      selector: '[appMyCheck]',
       providers: [{
        provide: NG_VALIDATORS,
        useExisting: forwardRef(() => MyCheckDirective),
        multi: true
      }]
    })
    export class MyCheckDirective implements Validator {
      isValid: any = false;
    
      @Input('appMyCheck') myValue;
       set setter (state) {
        this.isValid = state;
      };
      constructor() { }
    
      validate(formController: AbstractControl) {
       const validationState = !this.isValid ? {
          customKey: true
        } : null;
    
        console.log('validation state: ', validationState);
        return validationState;
      }
    
    
     
    }
    

    Hope useful