datepicker とは
この記事の目的
- Angular Material のdatepickerを組み込みます。
👇これより先は下記記事の内容を前提とします
datepicker の組み込み
[main.component.html
]を以下内容で書き換え。
main.component.html
<p>datepicker-sample works!</p>
<mat-form-field appearance="fill">
<mat-label>Choose a date</mat-label>
<!-- #docregion toggle -->
<input matInput [matDatepicker]="picker">
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<!-- #enddocregion toggle -->
</mat-form-field>
表示確認①
sh
ng serve --open
datepickerの日本ロケール化
日付フォーマットを日本ロケールに変更する(年/月/日 形式)
[angular/material-moment-adapter]導入
※日付フォーマット対応用
https://www.npmjs.com/package/@angular/material-moment-adapter/v/14.0.2
npm install @angular/material-moment-adapter
npm install moment
[main.component.ts
]を以下内容で書き換え。
main.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import {
MAT_MOMENT_DATE_FORMATS,
MomentDateAdapter,
MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import 'moment/locale/ja';
import 'moment/locale/fr';
import { CommonService } from '../common.service';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css'],
providers: [
{provide: MAT_DATE_LOCALE, useValue: 'ja-JP'},
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
{provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
],
})
export class MainComponent implements OnInit {
constructor(
private commonService:CommonService,
private _adapter: DateAdapter<any>,
@Inject(MAT_DATE_LOCALE) private _locale: string,
) { }
ngOnInit(): void {
}
getDateFormatString(): string {
if (this._locale === 'ja-JP') {
return 'YYYY/MM/DD';
} else if (this._locale === 'fr') {
return 'DD/MM/YYYY';
}
return '';
}
buttonClick(){
this.commonService.func01();
}
}
[main.component.html
]を以下内容で書き換え。
main.component.html
<div class="content" role="main">
<p>mainworks !</p>
<br>
<mat-form-field appearance="fill">
<mat-label>input date</mat-label>
<input matInput [matDatepicker]="dp">
<mat-hint>{{getDateFormatString()}}</mat-hint>
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp></mat-datepicker>
</mat-form-field>
</div>
表示確認②
ng serve --open