In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18.

Below is the code snippet I am currently working with:

<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 have successfully implemented the datepicker to allow selection from 1900 until the day before today's date.

Below is the TypeScript code for the date range:

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

You can view the project on Stackblitz.

Answer №1

If you want to display or hide form fields using *ngIf, you can create a function in your component to determine if the guardian should be visible. Here is an example:

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

In your template, you can use *ngIf with mat-form-field like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

Issue arises when attempting to submit multiple form fields with identical 'name' attributes, preventing the fields from being posted

Currently, I am facing a challenge with old HTML/JavaScript code. Some parts I have control over, while others are generated from an external source that I cannot manage. There is a form created dynamically with hidden fields. The form is produced using a ...

The Angular EventEmitter does not broadcast any modifications made to an array

Below is the code snippet: notes.service.ts private notes: Array<Note> = []; notesChanged = new EventEmitter<Note[]>(); getNotes() { this.getData(); console.log('getNotes()', this.notes); ...

Access a static class property through an instance

New and Improved Question: As I develop a client-side application, I am structuring an event-handling system inspired by the Redux framework. I have defined different event types as subclasses of a custom Event class. Each subclass includes its own stat ...

Raspberry Pi encountering a TypeError with Node.js async parallel: "task is not a function" error

I am new to nodejs, so I kindly ask for your understanding if my questions seem simple. I am attempting to use nodejs on a Raspberry Pi 3 to control two motors, and I keep encountering the error message "async task is not a function." Despite searching fo ...

Tips for utilizing the forEach method in Angular 2 without relying on ngFor?

I recently started learning Angular 2 and I am trying to figure out how to access array details using a forEach loop and apply certain conditions on it. Once I make the necessary changes, I want to display this data using ngFor. In Angular 1, this was ea ...

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

When I attempt to incorporate multiple sliders on a single page, I encounter difficulties in determining the accurate stopping position if the number of slides varies

I am having trouble setting the correct stop position for sliders with different numbers of slides on a page. When I have the same number of slides in each slider, everything works fine. However, I need to have a different number of slides in each slider ...

Error in Next.js: Trying to destructure an undefined object in useContext

While attempting to change the state of my cursor in a Next.js app using useContext, I encountered the following error: TypeError: Cannot destructure 'Object(...)(...)' as it is undefined. The goal is to update the state to isActive: true when h ...

The value of an Angular rxjs BehaviorSubject can be updated using the value property directly, without calling

While testing my code, I stumbled upon unexpected mutation. Perhaps I am doing something wrong. User constructor( public id: number, public education: Education[] ){} UserStateService private user = a new BehaviorSubject<User>(null); setUser(us ...

When deleting a row, the pagination feature in <mat-table> may encounter issues with the sticky

Struggling with a problem that I couldn't find a solution for online, so hoping to get some help here. I'm currently working on a dynamically-filled table where users can delete individual rows. The table has a sticky column and pagination, but I ...

What could be causing the input event not to be triggered consistently when I select or highlight text?

I have implemented a 4-digit pin field with a specific behavior: when a field is filled, the focus automatically shifts to the next field (the cursor moves to the next input field). If text in a field is deleted, the text in that field is also removed and ...

Transform a numerical variable into a string data type

I am faced with a situation where I have a variable named val which is currently set to the number 5. Now, my goal is to update the value of val so that it becomes a string containing the character "5". Could someone guide me on how to achieve this? ...

Hiding the header on a specific route in Angular 6

Attempting to hide the header for only one specific route Imagine having three different routes: route1, route2, and route3. In this scenario, there is a component named app-header. The goal is to make sure that the app-header component is hidden when t ...

Is there a method in JavaScript to access the object to which a function was originally bound?

I have a curiosity about making the code below function properly, capturing the logging as instructed in the comments. function somePeculiar(func) { var funcThis = undefined; // Instead of undefined, how can we access // ...

Exploring the functionality of the Angular snackbar feature

I have created a simple snackbar with the following code: app.component.ts: ngOnInit(){ this.dataService.valueChanges.pipe( filter((data) => data === true), switchMap(() => { const snackBarRef = this.matSnackBar.open ...

Cypress: Importing line in commands.ts is triggering errors

After adding imports to the commands.ts file, running tests results in errors. However, in commands.ts: import 'cypress-localstorage-commands'; /* eslint-disable */ declare namespace Cypress { interface Chainable<Subject = any> { c ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

Using Angular to prefill data in a few fields by using a Resolver, which will return an Observable within a subscriber

As I work on my Angular (8) application, I am looking to prepopulate certain fields from a service connected to the database. The use case involves prepopulating Address, Apartment, and other fields based on the zip code provided by another service. I att ...