ng2-datepicker how to change the date from typescript code?

4k views Asked by At

I am using the ng2-datepicker in my angular app and I want to update the date from the typescript file.

In the html template:

<ng2-datepicker [options]="optionsForMenuDate" [(ngModel)]="selectedDate" name="selectedDate"></ng2-datepicker>

It is binding to a moment object, so I am trying to update it like this (I have included moment in the angular solution):

this.selectedDate = this.moment(date);

Where date it the js Date object that I want to set the date to. This just sets the component to null though, even this this.selectedDate is not null.

console.log(this.selectedDate); // logs a moment object

Any ideas on how to achieve this?

2

There are 2 answers

2
Raj On

I was having the same issue and I got it working by following way.

The problem with your code is at below line,

[(ngModel)]="selectedDate"

Here, property 'selectedDate' should be of type 'DateModel' and not the moment object. The DateModel is defined at,

import {DateModel} from "ng2-datepicker";

And it has a following properties,

export declare class DateModel {
    day: string;
    month: string;
    year: string;
    formatted: string;
    momentObj: moment.Moment;
    constructor(obj?: IDateModel);
}

Now you need to set momentObj and formatted properties to get it working.

Here is the sample code,

let dateModel:DateModel = new DateModel();
let momentObj = moment('05-11-1986', "MM-DD-YYYY");
dateModel.momentObj = momentObj;
dateModel.formatted = momentObj.format();
this.selectedDate = dateModel;
0
YasirPoongadan On

you can update using setStartDate , test.ts file look like this

import { Component, ViewChild, OnInit, ElementRef } from '@angular/core';
import { DaterangePickerComponent } from 'ng2-daterangepicker';

@Component({
  selector: 'test',
  templateUrl: './test.html',
  styleUrls: ['./test.css']
})
export class TestComponent implements OnInit {

 // @ViewChild(DaterangePickerComponent) this line is very important
  @ViewChild(DaterangePickerComponent)
  private picker: DaterangePickerComponent;

  constructor() { }

  ngOnInit() {}

  ngAfterViewInit(){

    // get previous day for start date
    let startDate = new Date();
    startDate.setDate(startDate.getDate() - 1);

    // get next day for start date
    let endDate = new Date();
    endDate.setDate(endDate.getDate() + 1);

    this.picker.datePicker.setStartDate(startDate);
    this.picker.datePicker.setEndDate(endDate);

  }

}

and html look like this

<input type="text" class="form-control form-control2"  name="daterangeInput" daterangepicker [options]="options" />