I'm a beginner with angular 4 and I'm trying to implement a bootstrap ngbdatepicker in a website.
Here is my HTML code :
<div class="input-group ">
<input id="datepicker" class="form-control col-7" placeholder="{{dateWording}}" ngbDatepicker #date="ngbDatepicker" required pattern="[0-9]{4}[-][0-9]{2}[-][0-9]{2}">
<div class="input-group-append">
<button class="btn btn-outline-secondary picto-calender" (click)="date.toggle()" type="button"></button>
</div>
</div>
I tried to use events as (clic) or (blur) to access to my input value by using getDate(#date.value) but nothing worked properly. Here is my getDate method which return undefined value in the browser console.
getDate(date: any) {
this.date = date;
console.log(this.date);
}
So my two questions are :
Hope you'll can help me and sorry for my bad english !
You can use (ngModelChange) to get the date value.i have changed your code check this out
<div class="input-group ">
<input id="datepicker" class="form-control col-7" [(ngModel)]="model"
placeholder="" ngbDatepicker #date="ngbDatepicker" required
(ngModelChange)="select(model)" pattern="[0-9]{4}[-][0-9]{2}[-][0-9]{2}">
<div class="input-group-append">
<button class="btn btn-outline-secondary picto-calender"
(click)="date.toggle()" type="button"></button>
</div>
and your component.ts should like this
select(model){
console.log(model);
}
Working Example:
https://stackblitz.com/edit/angular-xnv11x?file=app/datepicker-popup.ts
you can use ngModel
to store the selected date in an Object of type NgbDateStruct
. it contains three properties month,year and day
. Then you can create a Date
object from that. In this example I am setting the value of the selected date in dateSelect
event of the datepicker, also the value is set in the object declared as ngModel
.
HTML
<div class="input-group ">
<input id="datepicker" class="form-control col-7" placeholder="{{dateWording}}" ngbDatepicker #date="ngbDatepicker" required pattern="[0-9]{4}[-][0-9]{2}[-][0-9]{2}" [(ngModel)]="currentDateObj" name="date" (dateSelect) = "onSelect($event)">
<div class="input-group-append">
<button class="btn btn-outline-secondary picto-calender" (click)="date.toggle()" type="button"></button>
</div>
</div>
ts file code
import {Component} from '@angular/core';
@Component({
selector: 'ngbd-datepicker-popup',
templateUrl: './datepicker-popup.html'
})
export class NgbdDatepickerPopup {
public model:any = {};
public selectedDate:Date;
public dateWording:string = "yyyy-mm-dd";
public currentDateObj:any = {};
onSelect(evt:any){
this.selectedDate = new Date(evt.year,evt.month-1,evt.day);
console.log(this.selectedDate);
}
}
Working demo : https://stackblitz.com/edit/angular-sskm4x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With