how to put a condition for mat date picker if it is less than 18 years need to show text box angular

1k Views Asked by At

I am trying to show text field based on the age validation if the age is less than 18 then only mat input field (Test box should appear)

Here is my current code

            <form [formGroup]="form">
          <mat-form-field>
            <input matInput [matDatepicker]="picker" placeholder="Choose a date"
            formControlName="pickerCtl">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
          </mat-form-field>
        <mat-form-field>
          <mat-label>Guardian Name</mat-label>
          <input matInput formControlName="guardianName" class="form-control" placeholder="Guardian Name">
            <span class="fa fa-lock lock_field"></span>
          </mat-form-field>
          <mat-form-field>
              <mat-label>Guardian Contact No</mat-label>
              <input matInput formControlName="guardianContactNo" class="form-control" placeholder="Guardian Contact No">
              <span class="fa fa-lock lock_field"></span>
          </mat-form-field>

Currently i was able to set datepicker to select date from 1900 till a current day before

Here is my TS

    minDate = new Date(1900, 0, 1);
    maxDate =  new Date(new Date().setDate(new Date().getDate()-1))

Please find Stackblitz URL

1

There are 1 best solutions below

9
On

You can use *ngIf to show/hide form-fields. Create a method in your component to determine if guardian should be visible. Something like this:

  get showGuardian(): boolean {
    const date = new Date().setFullYear(this.maxDate.getFullYear() - 18);
    return this.form.get('pickerCtl').value?.getTime() > date;
  }

And add an *ngIf to your mat-form-field in the template:

  <mat-form-field *ngIf="showGuardian">
    ..
  </mat-form-field>