Search code examples
angulartypescriptprimengangular13

Angular: Setting a date field by dropdown menu's selection


Let's say I have a dropdown menu, with the following options: "WORK", "RELEASE", "OPEN" and a second field, a calendar, which is initially an empty field. By setting the dropdown menu to "RELEASE" it should trigger the calendar field, setting it to today's date. The template looks like this (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>

In order to get today's date I have written the following function in the form.component.ts:

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

but I don't know how to trigger the dropdown menu. How can I do this?


Solution

  • You can work with onchange event. Refer to the table under the Events section.

    <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());
    }
    

    Sample Demo on StackBlitz


    Side note:

    The dateFormat should be dd-mm-yy instead of dd-mm-yyyy for <p-calendar>. Refer to DateFormat section.