Custom Formly Component not showing validation message on blur

199 Views Asked by At

I have a custom angular date picker component which uses ngb-datepicker and implements control value accessor. Now I create a formly component from this to use in my json form. This works fine but it's not showing validation message when user clicks in control and clicks away. The control just stays untouched even though it was touched. It's like blur is not triggered. What I am missing here?

Custom date picker control

import { Component, forwardRef, Input } from '@angular/core';
import {
  ControlValueAccessor,
  FormControl,
  NG_VALUE_ACCESSOR,
} from '@angular/forms';

@Component({
  selector: 'custom-date-picker',
  template: `
  <div class="input-group">
  <input
    class="form-control"
    placeholder="yyyy-mm-dd"
    name="dp"
    [formControl]="myControl"
    ngbDatepicker
    #d="ngbDatepicker"
    (keyup)="change($event)"
    (dateSelect)="change($event)"
  />
  <button
    class="btn btn-outline-secondary bi bi-calendar3"
    (click)="d.toggle()"
    type="button"
  ></button>
</div>
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NgbdDatepickerPopup),
      multi: true,
    },
  ],
})
export class NgbdDatepickerPopup implements ControlValueAccessor {
  myControl = new FormControl();
  model = '';
  private _onChange = (value: unknown) => {};
  private _onTouch = (value: unknown) => {};

  writeValue(obj: any): void {
    this.myControl.setValue(obj);
  }
  registerOnChange(fn: any): void {
    this._onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this._onTouch = fn;
  }

  change(event: unknown) {
    if (event instanceof Event) {
      const date = (event.target as HTMLInputElement).value;
      this._onChange(date);
      this._onTouch(date);
    }
  }
}

Formly Component

import { Component } from '@angular/core';
import { FieldType } from '@ngx-formly/core';

@Component({
 selector: 'formly-field-input',
 template: `
   <custom-date-picker [formControl]="formControl" [formlyAttributes]="field"></custom-date-picker>
   <div class="invalid-feedback" style="display: block;">
            <formly-validation-message *ngIf="showError" [field]="field"></formly-validation-message>
    </div>
 `,
})
export class FormlyFieldInput extends FieldType {}
1

There are 1 best solutions below

0
Emz On

I managed to fix this by making _onTouch public and updating the template for custom-date-picker to bind to the blur event (blur)="_onTouch($event)".