-1

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

Mr.M
  • 1,472
  • 3
  • 29
  • 76

1 Answers1

0

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>
Felix
  • 1,337
  • 10
  • 10
  • thanks for the answer that ngif i need to put for all two mat field right – Mr.M May 19 '21 at 18:18
  • You can also create a ng-container or a div element around both form fields and at the *ngIf to that element. – Felix May 19 '21 at 18:21
  • initially do i need to set the showGuardian as true / false in top of my code – Mr.M May 19 '21 at 18:31
  • by default itself text box is coming – Mr.M May 19 '21 at 18:39
  • i haev updated here https://stackblitz.com/edit/mat-datepicker-ang?file=src%2Fapp%2Fdatepicker-overview-example.ts – Mr.M May 19 '21 at 18:45
  • You fill the initial value of your date field with the current date. So this matches the criteria and the fields will be visible. Don't add an initial value if you don't want the fields to be visible initially. – Felix May 19 '21 at 20:13
  • can you please update my stackblitz it will be really helpful – Mr.M May 19 '21 at 20:23
  • https://stackblitz.com/edit/mat-datepicker-ang-b5c7ke – Felix May 19 '21 at 20:25
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232610/discussion-between-mr-m-and-felix). – Mr.M May 19 '21 at 20:54