Home > Enterprise >  Angular: Setting a date field intially
Angular: Setting a date field intially

Time:04-07

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 >
        <div >
            <div >
                <label >Status</label>
                <p-dropdown
                    [options]="workStatus"
                    [showClear]="true"
                    formControlName="workingStatus"
                    >
                </p-dropdown>
            </div>
            <div >
                <label >Date</label>
                <p-calendar formControlName="getWorkDate"
                            dateFormat="dd-mm-yyyy"
                            dataType="localdate"
                            appendTo="body"
                            >
                </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 trigger the dropdown menu. How can I do this?

CodePudding user response:

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)"
    
    >
</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.

CodePudding user response:

You can bind change event with dropdown like this and based on your response you can make it possible.

Example

HTML :

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

In the TS file you can put conditions based on that you can enable your calendar.

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

Function which have already created.

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