I am using ngx-bootstrap for date picker, my date picker has input format "dd/MM/yyyy" like 25/07/2019

so I create an component for capturing the date and convert it into my reactive form (because mysql accept date as yyyy-mm-dd). I use ngModel in input and doing value changes everytime user did input value.

the code as follow :

import { environment } from './../../../environments/environment';
import { Component, OnInit, Input } from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { FormGroup } from '@angular/forms';
import * as moment from "moment";

@Component({
  selector: 'app-input-date',
  templateUrl: './input-date.component.html',
  styleUrls: ['./input-date.component.css']
})
export class InputDateComponent implements OnInit {
    @Input() form: FormGroup;
    @Input() fieldName: string;
    @Input() fieldDescription: string;

    datePickerConfig: Partial<BsDatepickerConfig>;
    tempDate: any ; 
    isInvalid: boolean;

  constructor() {
    this.datePickerConfig = Object.assign(
        {},
        {
          containerClass: "theme-dark-blue",
          dateInputFormat: environment.dateFormat
        }
      );
  }

  ngOnInit() {
    let theDate = this.form.get(this.fieldName).value;
    if( theDate != ""){
        this.tempDate = moment(theDate, environment.mysqlDateFormat).format(environment.dateFormat);
    }
  }

  get myField()
  {
      return this.form.get(this.fieldName);
  }

  // For date
  onDateModelChange(event)
  { 
    if(this.tempDate != ""){
        this.form.patchValue({
            [this.fieldName]: moment(this.tempDate, environment.dateFormat).format(environment.mysqlDateFormat)
        });
    }else{
        this.form.patchValue({
            [this.fieldName]: ""
        });
    }
    console.log(this.form.get(this.fieldName).errors);
  }

}
<input type="text" class="form-control mydatepicker" 
placeholder="" id="mydatepicker"
[ngClass]="{'has-error': myField.touched && myField.hasError('required')}"
[(ngModel)]="tempDate" (ngModelChange)="onDateModelChange($event)" [ngModelOptions]="{standalone: true}"
[bsConfig]="datePickerConfig" bsDatepicker>

Now, I need to display error if the user forgot to enter the date or the date input was invalid. I set the reactiveform using Validators.required like

this.form = this.formBuilder.group({ dateOfBirth: ["", Validators.required]});

But since I use ngModel it wont validated. I just wonder how to get the field validated everytime user click / entering the input (pristine or dirty)

I tried this code on my InputDateComponent but it always return null

onDateModelChange(event){
console.log(this.form.get(this.fieldName).errors);
}

If you have simple solutions for date format, I would like to know as well..

0 Answers