Angular: Populating a date field using a dropdown menu selection

Imagine there's a dropdown menu in my application, with options like "WORK", "RELEASE", and "OPEN". There's also a calendar field that is initially empty. When I choose the option "RELEASE" from the dropdown menu, I want it to automatically select today's date on the calendar field. The code snippet for this scenario can be found in form.component.html:

<form [formGroup]="form">
    <div class="flex">
        <div class="col-3">
            <div class="flex flex-row align-items-center">
                <label class="col-6">Status</label>
                <p-dropdown
                    [options]="workStatus"
                    [showClear]="true"
                    formControlName="workingStatus"
                    class="col-6">
                </p-dropdown>
            </div>
            <div class="flex flex-row align-items-center">
                <label class="col-6">Date</label>
                <p-calendar formControlName="getWorkDate"
                            dateFormat="dd-mm-yyyy"
                            dataType="localdate"
                            appendTo="body"
                            class="col-6">
                </p-calendar>

To ensure that today's date is selected on the calendar, I have implemented a function in form.component.ts:

selectTodaysDate(DateToday: number[]) {
    const todayDate = new Date().getDate();
    this.form.patchValue({getWorkDate: DateToday.find(today => today == todayDate)});
}

Now, the challenge lies in triggering the dropdown menu when "RELEASE" is selected. How can I achieve this interactivity?

Answer №1

If you want to handle changes using the onchange event, take a look at the events table in the Dropdown documentation.

<p-dropdown
    [options]="workStatus"
    [showClear]="true"
    formControlName="workingStatus"
    (onChange)="onDropdownChange($event.value)"
    class="col-6"
    >
</p-dropdown>
onDropdownChange(value) {
  if (value == 'RELEASE')
    this.form.controls["getWorkDate"].setValue(new Date());
}

Check out a Sample Demo on StackBlitz


Just a heads up:

When using <p-calendar>, make sure the dateFormat is dd-mm-yy and not dd-mm-yyyy. For more information, refer to the DateFormat section.

Answer №2

To link the change event to a dropdown menu, follow these steps and adjust accordingly based on your requirements.

For example:

HTML :

<p-dropdown  
[options]="workStatus"
[showClear]="true"
formControlName="workingStatus"
class="col-6"  
(onChange)="onChange($event)">
</p-dropdown>

In the TS file, you can set conditions that will determine whether to enable your calendar.

onChange(event) {
    console.log('event :' + event);
    console.log(event.value);
    if(event.value === "RELEASE"){
     this.selectTodaysDate(params); // Function call
   // Alternatively, you can update form value like this
     const todayDate = new Date().getDate();
     this.form.patchValue({getWorkDate: DateToday.find(today => today == todayDate)});
   }
}

An existing function is available for use:

selectTodaysDate(DateToday: number[]) {
        const todayDate = new Date().getDate();
        this.form.patchValue({getWorkDate: DateToday.find(today => today == todayDate)});
    }

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

The CORS Policy has prevented Angular from accessing the header, as the request header field for authentication is restricted

After reviewing a multitude of similar questions regarding CORS and headers, I have attempted various solutions but I am still encountering this error specifically in Google Chrome. Access to XMLHttpRequest at 'https://service.domain.com/clientlist&ap ...

The search for 'partition' in 'rxjs' did not yield any results

Recently, I attempted to incorporate ng-http-loader into my Angular project. After successfully installing the ng-http-loader package, I encountered an error during compilation. The specific error message displayed was: export 'partition' was ...

Several of your tests performed a complete page refresh

While conducting unit tests in Angular, I encountered the following error: ALERT: 'Add Success!' Chrome 58.0.3029 (Windows 10 0.0.0) ERROR Some of your tests triggered a full page reload! Chrome 58.0.3029 (Windows 10 0.0.0): Executed 0 of 1 ER ...

Can someone please explain how to bring in the Sidebar component?

click here for image description check out this image info An issue arises as the module '@components/Sidebar' or its type declarations cannot be located.ts(2307) Various attempts were made, including: import Sidebar from '@components/Sid ...

Tips on efficiently utilizing stored information in Ionic and Angular applications

I am facing an issue where I can only access my variable inside the this.storage.get function. How can I retrieve this stored data? Here is the content of tab2.page.html: <ion-toolbar> <ion-title> Stats </ion-title> &l ...

The art of gracefully defining universal types in TypeScript

In the scenario where I have a type type myObject = object; and want it to be accessible globally across all modules transpiled with tsc, is there a graceful method to define a global type alias in TypeScript? ...

Angular 2 - What is the latest method for bootstrapping correctly?

I am looking to integrate Angular 2's security features, particularly CSRF, which requires the use of the XSRFStrategy provider. However, the current bootstrap process I am using is not up to date to support this provider. This leads to the challenge ...

Using React-Bootstrap with TypeScript in your project

I'm currently working on creating a navigation bar using react-bootstrap. I've already installed the node-module as follows: "@types/react-bootstrap": "^0.32.11",. However, when I try to use it in my hello.tsx component, I encounter a compile err ...

Tips for Successfully Transmitting Information via Mat-Dialog

Having trouble passing data from a dialog back to the parent component. Specifically, I'm struggling with updating the value of an array in the `afterClosed` function. I've tried using `patchValue` and `setValue`, but it doesn't seem to be w ...

The attribute 'split' is not found on the never data type

I have a function that can update a variable called `result`. If `result` is not a string, the function will stop. However, if it is a string, I then apply the `split()` method to the `result` string. This function always runs successfully without crashin ...

Removing Bootstrap Styles in Angular Single Page Applications

Currently, I am in the process of customizing the styles for an ASP.Net Core 2.2 Angular SPA. Upon examination, I noticed that a specific file webpack:///./node_modules/bootstrap/scss/_reboot.scss is being generated at runtime. To take control of the styl ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Unable to retrieve the data property from the Axios response object following a successful GET request: The property 'data' is not present in the type 'void'

Currently, I am working on a personal project using React and TypeScript to enhance my skills. However, I have encountered a puzzling error in the following code snippet, which involves using Axios to fetch data: const fetchItem = async () => { const ...

Encountering error TS2305 in Visual Studio Code while working with moment.js in an example from an Angular Material

After referencing the code snippet from https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings, I encountered an issue. While the code successfully compiles and runs, Visual Studio Code flagged an ...

Moving the marker does not update the address

When the dragend event is triggered, the Getaddress function will be called in the following code: Getaddress(LastLat, LastLng , marker,source){ this.http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+LastLat+ &apos ...

Angular's Dynamic Reactive Forms

I encountered an issue while using Typed Reactive Forms in Angular 14. I have defined a type that connects a model to a strict form group. The problem arises specifically when utilizing the Date or Blob type. Note: I am working with Angular 14. Error: src/ ...

Tips for transferring data between parent and child components multiple times in a React application

For my Angular 2 application, I am working on a search feature where the search form and result display are on the same page. Using routing, the parent component houses the search form with multiple fields while the child component retrieves results from t ...

Encountering an issue in a Next.js application while building it, where an error is triggered because the property 'protocol' of 'window.location' cannot be destructured due to being undefined

While building my nextjs application, I encountered the following error. My setup uses typescript for building purposes, although I am only using JavaScript. Build error occurred: TypeError: Cannot destructure property 'protocol' of 'window ...

Ways to switch up the titles on UploadThing

Recently, I started working with the UploadThing library and encountered a situation where I needed to personalize some names within the code. Here is what I have so far: Below is the snippet of code that I am currently using: "use client"; imp ...

How can a material progress spinner be inserted into the Angular Ag-Grid overlayNoRowsTemplate?

I'm attempting to include a mat-progress-spinner within my agGrid when there are no rows to display. Here's an example that works: private overlayNoRowsTemplate = '<p>No rows to show.</p>'; However, when I attempt to add ...