またバリデーションにも対応させます。
npm install jquery --save
npm install jquery-datetimepicker --save
"styles": [
"src/styles.scss" ,
"node_modules/jquery-datetimepicker/build/jquery.datetimepicker.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js" ,
"node_modules/jquery-datetimepicker/build/jquery.datetimepicker.full.min.js"
]
import { Component } from '@angular/core';
// jquery
declare var $: any;
ng g component page01
const routes: Routes = [
{ path: 'page01', component: Page01Component },
{ path: '**', component: Page01Component }, // 追加
];
<input type="text" class="form-control jquery-datetimepicker" name="test-date" formControlName="datepicker" autocomplete="off">
<pre class="debug">
{{ registerForm.value | json }} <br>
Validation: {{ registerForm.get( 'datepicker' ).valid }}
</pre>
import { Component, OnInit } from '@angular/core';
// jquery
declare var $: any;
@Component({
selector: 'app-page01',
templateUrl: './page01.component.html',
styleUrls: ['./page01.component.scss']
})
export class Page01Component implements OnInit {
constructor() { }
ngOnInit() {
// ===== jquery-datetimepicker =====
let _this = this;
$.datetimepicker.setLocale('ja'); // 日本語化
$('input.jquery-datetimepicker').datetimepicker({
lang: 'ja',
timepicker: false,
format:'Y-m-d',
onSelectDate:function( date ){
var year = date.getFullYear();
var month = ("0"+(date.getMonth() + 1)).slice(-2);
var date = ("0"+date.getDate()).slice(-2);
var date_formatted = year + '-' + month + '-' + date;
_this.registerForm.get('datepicker').setValue( date_formatted );
}
});
// ===== jquery-datetimepicker =====
}
}
これでコンポーネントは完成です。
jquery-datetimepicker で日付を選択時に、_this.registerForm.get('datepicker') にも値が反映されます。