To simplify things, you can create a property called fecha with a setter function in your Component:
year:number;
month:number;
get fecha():any
{
return new Date(this.year,this.month-1,1)
}
console.log(year,month,fecha);
If you are using ngModel, you can separate the [(ngModel)] into:
<select [value] = "exp.StartDate.Month" (input)="updateMonth($event.target.value)" >
...
</select>
<select [value] = "exp.StartDate.Year" (input)="updateYear($event.target.value)">
//In your component
updateMonth(month:number)
{
this.exp.StartDate.Month=month;
this.exp.StartDate.Value=this.exp.StartDate.Year+'-'+this.exp.StartDate.Mont+'-1';
}
updateYear(year:number)
{
this.exp.StartDate.Year=year;
this.exp.StartDate.Value=this.exp.StartDate.Year+'-'+this.exp.StartDate.Mont+'-1';
}
Alternatively, you can implement a custom form control to manage the value. Below is a sample code with a custom form control that expects a JavaScript Date Object (if you are using a String, you may need to modify the code):
import { Component, forwardRef, HostBinding, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
//TODO: Change input to select
@Component({
selector: 'app-month-year',
template: `
<input [disabled]="disabled" [value] = "month" (input)="updateMonth($event.target.value)" >
<input [disabled]="disabled" [value] = "year" (input)="updateYear($event.target.value)">
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MonthYearComponent),
multi: true
}
]
})
export class MonthYearComponent implements ControlValueAccessor {
month:number;
year:number;
// Allow the input to be disabled, and when it is make it somewhat transparent.
@Input() disabled = false;
@Input('value') value;
onChange: any = () => { };
onTouched: any = () => { };
updateMonth(month:number)
{
this.month=month;
this.value=this.getDate(); //<--change the "value"
this.onChange(this.value);
}
updateYear(year:number)
{
this.year=year;
this.value=this.getDate(); //change the value
this.onChange(this.value);
}
constructor() { }
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
writeValue(value) { //<--when receive a value
if (value) {
this.month=value.getMonth()+1;
this.year=value.getFullYear();
}
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
//It's better use a function to return the value
private getDate()
{
const date=new Date();
date.setFullYear(this.year,this.month-1,1);
return date;
}
}