How to set value for ngbdatepicker in angular 8

Dung Do Tien Oct 26 2020 91

I have a form search that has two fields are Start date and End date using ngbdatepicker to make datetime picker. But I can set the value to them but it not display the value when the page initial finished.

This is my form:

<div class="input-group col-sm-12 col-md-6 col-lg-3">
    <input class="form-control" placeholder="--Creation date ranged from--" name="startDate"
        [(ngModel)]="filter.startDate" ngbDatepicker #startDate="ngbDatepicker">
    <div class="input-group-append">
        <div class="input-group-text" (click)="startDate.toggle()">
            <i class="fa fa-calendar" style="cursor: pointer;"></i>
        </div>
    </div>
</div>
<div class="input-group col-sm-12 col-md-6 col-lg-3">
    <input class="form-control" placeholder="--Creation date ranged to--" name="endDate"
        [(ngModel)]="filter.endDate" ngbDatepicker #endDate="ngbDatepicker">
    <div class="input-group-append">
        <div class="input-group-text" (click)="endDate.toggle()">
            <i class="fa fa-calendar" style="cursor: pointer;"></i>
        </div>
    </div>
</div>

and this is my ngOnInit event

 filter: WorkingUserReportFilterModel;
 ngOnInit() { 
    this.filter = new WorkingUserReportFilterModel();
    this.filter.endDate = new Date();
    this.filter.startDate  = new Date();
  }

I want to initial value for them to the current date but they did not display in the browser. Please suggest to me if you know any solution.

Have 1 answer(s) found.
  • To set value for ngbDatepicker you need set with format object as below:

    var setDate = { year: 2020, month: 10, day: 10 }; 

    In your case, you can do as below :

    filter: WorkingUserReportFilterModel;
    currentDate = new Date();
    ngOnInit() { 
        const objCurrentDate = { year: this.currentDate.getFullYear(), month: this.currentDate.getMonth() + 1, day: this.currentDate.getDate() };
    
        const objBeginDate = { year: this.currentDate.getFullYear(), month: this.currentDate.getMonth()+ 1, day: 1 };
    
        this.filter = new WorkingUserReportFilterModel();
        this.filter.endDate = objCurrentDate;
        this.filter.startDate = objBeginDate;
      } 

    I hope it helpful for you.

    Sandeep Kumar Oct 26 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips