AleksandarMihailovic
AleksandarMihailovic

Reputation: 125

How to initialize an Angular Material Datepicker input form field?

I'm trying to format my date picker. I don't know the way. I tried inserting a moment.js library that I don't know how to use but copying it from the internet. Now my date picker returns an object moment and I don't know how to format this.

Component

this.form = this.fb.group({
  deliveryDate: [this.deliveryDate], // i try to set here instead this.delieryDate null or moment() or everythink.....
  address: [null, [Validators.required, Validators.minLength(5)]],
  phone: [null, [Validators.minLength(9),Validators.maxLength(19)]],
  city: [null, [Validators.required, Validators.minLength(5)]],
  data: this.fb.array([this.createContact()])
});

Template

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Izaberite datum narudzbe"
      formControlName="deliveryDate">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Upvotes: 0

Views: 7210

Answers (1)

Christopher Peisert
Christopher Peisert

Reputation: 24114

The simplest way to set the initial date for an Angular Material Datepicker is to set an initial date value when constructing the form control.

Component

import {Component} from '@angular/core';
import {FormBuilder, FormControl, Validators} from '@angular/forms';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  deliveryForm = this.fb.group({
    deliveryDate: [new Date()],
    address: [null, [Validators.required, Validators.minLength(5)]],
    phone: [null, [Validators.minLength(9),Validators.maxLength(19)]],
    city: [null, [Validators.required, Validators.minLength(5)]]
  });

  constructor(private fb: FormBuilder) { }
}

HTML Template

<form [formGroup]="deliveryForm">
  <mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Izaberite datum narudzbe"
         formControlName="deliveryDate">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="address" placeholder="Address"
      autocomplete="address-line1">
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="phone" placeholder="Phone number"
      autocomplete="tel-national">
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="city" placeholder="City" autocomplete="address-level2">
  </mat-form-field>
</form>

Resulting Form

Example form with datepicker

Upvotes: 3

Related Questions