See this stackblitz
https://stackblitz.com/edit/angular-dcr7ub
Note the two way binding in the form [(ngModel)]="date"
links to date
in app.component.ts
though you could do this using reactive forms.
app.component.html
<form (ngSubmit)="onSubmit()" #f="ngForm">
<div class="example-container">
Form
<mat-form-field>
<input matInput [(ngModel)]="date" [matDatepicker]="picker" name="date" placeholder="Choose a date" />
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
There are a few tricky things I encountered implementing this:
import {MatDatepickerModule} from '@angular/material/datepicker';
import {MatFormFieldModule, MatInputModule} from '@angular/material';
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import { MatMomentDateModule } from "@angular/material-moment-adapter";
The last one being as you have to provide a DateAdapter
for dealing with dates (the datepicker is agnostic about this).
- Remember to include a theme in
styles.css
, I used:
@import '@angular/material/prebuilt-themes/deeppurple-amber.css';
So in my example the date is a moment (https://momentjs.com/) object hence the .format()
in:
onSubmit() {
console.log((<any>this.date).format());
}