String Name
String Name

Reputation: 202

Angular 4+ - How to fetch date from input datepicker

I'm new to angular.

I have an input date picker. I want to get/fetch the date selected in the date picker.

Code: Html file:

 <input class="form-control m-input " id="m_datepicker_2_validate" placeholder="Select Date" readonly="" type="text">

I'm trying to console.log the selected date.
In the component.ts file I've added a variable staff_date_booking : Date; and created a function

bookStaffEmployeeDate(){
        console.log("This is the DATE:", this.staff_book_date);
    }

and in the html I've added

 <input [ngModel]="staff_book_date | date:'yyyy-MM-dd'" class="form-control m-input " id="m_datepicker_2_validate" placeholder="Select Date" readonly="" type="text">

Once the date is selected I'm calling this function on (click) but I'm getting this.staff_book_date as undefined.

How can I store the selected date in a variable like staff_book_date

Upvotes: 2

Views: 4535

Answers (2)

Sarthak Aggarwal
Sarthak Aggarwal

Reputation: 2312

Create a property in your .ts file and make a two way binding with it in your .html

Make the following changes

.component.ts

staff_book_date : any;

bookStaffEmployeeDate(){
        console.log("This is the DATE:", this.staff_book_date);
}

component.html

<input [(ngModel)]="staff_book_date" class="form-control m-input " id="m_datepicker_2_validate" placeholder="Select Date" type="date">
<button (click)="bookStaffEmployeeDate()">Click Me</button>

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

Don't use pipes inside ngModel. Also, use the two-way binding in the ngModel

<input [(ngModel)]="staff_book_date" 

Upvotes: 1

Related Questions