I am using jquery-datetimepicker within the angular projects. But when I select the date in the date picker the value is not bound to the form control.
I tried so far.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
startDate: ['', Validators.required],
});
}
onSubmit() {
console.log('value: ', this.myForm.value);
console.log('the whole form and its controls: ', this.myForm);
}
ngOnInit() {
(window as any).$('.pickDateOneTimeStartDate').datetimepicker({
allowInputToggle: true,
timepicker: false,
format: 'M d, Y',
minDate: Date.now,
scrollMonth: false,
scrollInput: false,
});
}
}
app.component.html
<form class="form-horizontal" [formGroup]="myForm" (ngSubmit)="onSubmit()">
<hello [myForm]="myForm"></hello>
<button type="submit">Submit</button>
</form>
hello.component.ts
import { Component, Input } from '@angular/core';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
} from '@angular/forms';
@Component({
selector: 'hello',
template: `
<div class="form-group" [formGroup]="myForm">
<div class="pickDateOneTimeStartDate">
<input formControlName="startDate" aria-label="Start Date" [ngClass]="{
'is-invalid':
myForm.controls['startDate'].errors
}" class="form-control">
<div *ngIf="myForm.hasError('required', 'startDate')" class="invalid-feedback">
This field is required
</div>
</div>
</div>
`,
styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
@Input() myForm: FormGroup;
ngOnInit() {}
}
stackblitz implementation
when I add onChangeDateTime on the date picker the value in the form objects gets updated but is still not shown in the input box.
updated:
var self = this;
(window as any).$('.pickDateOneTimeStartDate').datetimepicker({
allowInputToggle: true,
timepicker: false,
format: 'M d, Y',
minDate: Date.now,
scrollMonth: false,
scrollInput: false,
onChangeDateTime: function (dp, $input) {
self.myForm.value.startDate = $input.val();
},
});
output:
{
"startDate": "Jun 30, 2022"
}
just change the function with
onChangeDateTime: function (dp, $input) {
self.myForm.controls.startDate.setValue($input.val());
},