Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directive @Input variable not getting update when component update the value

I am trying to dynamically validate the custom-text-input based on service call result. If its true means jumpyId is available to use otherwise show error. My issue right now is when I update this.isAvailable from fromEvent its not reflecting the value in custom directive. I am expecting if api call return true, then directive should receive true otherwise false.

AvailableDirective.ts

import { Directive, forwardRef, Input } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
@Directive({
  selector: 'custom-text-input[vendorAvailable][formControlName],custom-text-input[vendorAvailable][formControl],custom-text-input[vendorAvailable][ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: AvailabilityDirective, multi: true }
  ]
})
export class AvailabilityDirective implements Validator {

  @Input('available') available: boolean;
  validate(c: AbstractControl): { [key: string]: any } {
    console.log("valid", this.available);
    if (!this.available) {
      return {
        available: false
      };
    }
    return null;
  }
}

EventObservable:

fromEvent(this.custom.nativeElement, 'keyup').pipe(
      map((event: any) => {
        return event.target.value;
      })
      , debounceTime(1000)
      , distinctUntilChanged()
    ).subscribe((text: string) => {
      this.myService.isAvailable(text).subscribe((res) => {
        console.log(res);
        if (res) {
          this.isAvailable = true;
        } else {
          this.isAvailable = false;
        }
      }, (err) => {
        console.log(err);
      });
    });

template:

<custom-text-input *ngIf="drawer"
                                           label="JumpyId"
                                           [(ngModel)]="jumpyId"
                                           id="jumpyId"
                                           name="jumpyId"
                                           required
                                           [available]="isAvailable"
                                           #custom>
                        </custom-text-input>
like image 229
Darksilence Avatar asked Oct 29 '25 11:10

Darksilence


1 Answers

Add an onChanges that watches for changes to available

onChange: () => void;

registerOnValidatorChange(fn: () => void): void {
  this.onChange = fn;
}

ngOnChanges(changes: SimpleChanges): void {
  if ('available' in changes) {
    if (this.onChange) {
      this.onChange();
    }
  }
}

If my validation directives rely on another input I use this validator base

https://stackblitz.com/edit/angular-cfexiy

like image 83
Adrian Brand Avatar answered Oct 31 '25 01:10

Adrian Brand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!