Home > other >  how can I move a string date to a new component with 3 fields
how can I move a string date to a new component with 3 fields

Time:10-20

I have a component called DateComponent, and it contains 3 inputs (year/month/day). I also have a component which contains a formGroup and has a formControlname date which is like yyyy-mm-dd.

If I want to go through the FormGroup path, how can I get the data from DateComponent nicely as yyyy-mm-dd to the form in parent component?

I tried to use ControlValueAccessor, but the problem is I have 3 ngmodel (day, month, year) in DateComponent while in parent there is one which is Date.

I really prefer not to break down my formControl from date to 3 fields. Any thoughts or solution.

CodePudding user response:

you can maybe do something like this

let date = 10
let month = 1
let year = 2019

let finalDate = new Date()
finalDate = new Date(finalDate.setDate(date))
finalDate = new Date(finalDate.setMonth(month))
finalDate = new Date(finalDate.setFullYear(year))
console.log(finalDate)

the final output would be something like this

2019-02-10T04:47:37.886Z

if you want to remove the time you can do that using datepipe

console.log(this.datePipe.transform(finalDate, 'yyyy-MM-dd'))

the output of above console.log would you be

2019-02-10

CodePudding user response:

When we make a custom form control extending ControlValueAccessor the important part is when we define registerOnChange and when "something" change we call to the function.

A simple .html

<input [ngModel]="year" (ngModelChange)="year= $event;change()">
<input [ngModel]="month" (ngModelChange)="month= $event;change()">
<input [ngModel]="day" (ngModelChange)="day= $event;change()">

See that each change in an input call to the function "change()"

The important part:

  year:number;
  month:number;
  day:number;
  constructor() { }

  onChange:any; //<--define a function OnChange

  //here we give value to our function "onChange"
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  //each change of the inputs
  change(){
    if (this.year && this.month && this.day)
    {
      const date=new Date(this.year,this.month-1,this.day)
      this.onChange(date); //<--we call to the function onChange
                           //we pass as argument the value we want to get our
                           //control
    }

   //the writeValue is executed onTime at first with the value
   //of the control
   writeValue(value: any[]|any): void {
    this.year=value?value.getFullYear():null;
    this.month=value?value.getMonth() 1:null;
    this.day=value?value.getDate():null;
  }
  • Related