Reputation: 847
I am creating a POST request to an API, and one of the fields which throws an error is a mat-datepicker
field, since it's inside the ngOnInit()
call(and nothing is yet selected, I guess). Fields such as name
, email
etc. behave well, but I'm having trouble getting a value out of the datepicker field... How could I send that value as well when submitting the form?
My attempt was this:
ngOnInit() {
this.myForm = new FormGroup({
date_of_birth: new FormControl(new Date().toISOString(), [
Validators.required,
this.backendValidation.bind(this, 'date_of_birth')
])
})
}
<mat-form-field>
<mat-label>Date</mat-label>
<input matInput [matDatepicker]="date_of_birth" formControlName="date_of_birth" />
<mat-datepicker-toggle matSuffix [for]="date_of_birth"></mat-datepicker-toggle>
<mat-datepicker #date_of_birth></mat-datepicker>
</mat-form-field>
Upvotes: 0
Views: 16184
Reputation: 1040
In HTML:
<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
<mat-form-field>
Date
<input matInput [matDatepicker]="picker" formControlName="date_of_birth" />
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</form>
<button (click)="get()">get</button>
TS:
this.empForm = this.fb.group({
date_of_birth: new FormControl(new Date(), [
Validators.required
])
});
To console:
get(){
console.log(this.empForm.get('date_of_birth').value);
}
Hope this will help you. If any issues, then I think its problem with the custom validator you have - this.backendValidation.bind(this, 'date_of_birth')
.
Hope this works !
Upvotes: 4