6

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!

1 Answer 1

3

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 };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.