Search code examples
angularionic-frameworkionic3custom-componentrequired

Angular custom component required


is there a way that I can use the required attribute on my custom component? My component looks like this:

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

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DatePickerComponent),
  multi: true
};

@Component({
  selector: 'date-picker',
  templateUrl: 'date-picker.html',
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class DatePickerComponent implements ControlValueAccessor {
  @Input("label") label: string;
  @Input("pickerFormat") pickerFormat: string;
  @Input("displayFormat") displayFormat: string;
  @Input("max") max: string;
  @Input("min") min: string;
  @Input("cancelText") cancel: string;
  @Input("doneText") done: string;
  @Input("valid") valid: boolean;
  @Input("disabled") disabled: boolean;

  private _mobile: boolean = false;
  private _date: string;

  constructor(private plt: Platform) {
    if (plt.is("mobile"))
      this._mobile = true;
  }

  get date(): string {
    return this._date;
  }

  set date(value: string) {
    this._date = value;
    this.onChange(this._date);
  }

  public onChange(value: any): void { }

  public onTouched(): void { }

  public writeValue(obj: any): void {
    if (this.date !== obj) {
      this.date = obj;
    }
  }

  public registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  public registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}

I want my form where I use this component to disable the submit button if the _date (or date) is null or not a valid date (because of min/max). Is there any way I can implement something like this for my component?

Thanks for your help!


Solution

  • Make it implement the Validator interface :

    export class DatePickerComponent implements ControlValueAccessor, Validator {...}
    

    it only requires a single function, validate :

    public validate(c: FormControl) {
      // Business logic. If no error, return null, if not : 
      return { required: true };
    }