Angular – How to set Angular Material datepicker Birth Date to max of 18 years

Issue

In Angular-12, I am using Material datepicker for date of birth:

Component:

tomorrow = new Date();
constructor(
  private router: Router,
) {
  this.tomorrow.setDate(this.tomorrow.getDate());
}

HTML

<div class="col-12 col-md-6">
  <label for="dob">Date of Birth:<span style="color:red;">*</span></label>
  <div class="form-group">

    <mat-form-field fxFlex="100%" fxFlex.gt-sm>
      <input matInput [matDatepicker]="dob" placeholder="Choose a date" [max]="tomorrow" formControlName="dob" readonly required>
      <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle>
      <mat-datepicker #dob></mat-datepicker>
    </mat-form-field>
  </div>
  <div *ngIf="fp.dob.touched && fp.dob.invalid">
    <div *ngIf="fp.dob.hasError('required')">
      <div class="text-danger">
        Date of Birth is required!
      </div>
    </div>
  </div>
</div>

I want to set the min date to 18 years so that any candidate below 18 years will not be able to register.

How do I achieve this?

Thanks

Solution

If you want to limit it to 18 year olds. You actually want to set the max to todays date minus 18 years, not the min.

In your component constructor something like this(although I would recommend you use ngOnInit instead for components).

maxDob: Date;
constructor(
  private router: Router,
) {
  const today = new Date();
  this.maxDob = new Date(
    today.getFullYear() - 18,
    today.getMonth(),
    today.getDate()
  );
}

And make sure to change your html as well

<input matInput [matDatepicker]="dob" placeholder="Choose a date" [max]="maxDob" formControlName="dob" readonly required>

Here’s a stackblitz example with ngOnInit

https://stackblitz.com/edit/angular-material-4erepd?file=app/app.component.ts

Answered By – Faz

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.