Search results

JSON Data binding with DatePicker in Angular DatePicker component

14 Apr 2021 / 1 minute to read

In most of the real cases, the model data will be available with JSON format only. Here we have showcased DatePicker component by setting JSON string to value property. In this JSON, we have used ISO formatted date string which is frequently used date format to get proper date and time value without any misreading. Also our DatePicker component supports the ISO formatted date value, so parsed JSON value can be directly set to DatePicker model.

Source
Preview
app.component.ts
app.module.ts
main.ts
styles.css
Copied to clipboard
import { Component } from '@angular/core';

export interface User {
    selectedDate: Date;
}
export interface JSONUser {
    selectedDate: string;
}
@Component({
    selector: 'app-root',
    template: `
    <!-- To Render DatePicker -->
    <ejs-datepicker id="datepicker" width='245px' [(value)]='user.selectedDate' (change)='onChange($event)'></ejs-datepicker>
    <div class="valuestring">
    <b>User model</b>:  <br/>{{user | json }}
    <br/><br/>
    <b>JSON Data</b>: <br/>{{ model_result }}
    <br/><br/>
    </div>`
})
export class AppComponent {
    public user: User;
    public JSONData: JSONUser = JSON.parse('{ "selectedDate": "2018-12-18T08:56:00+00:00"}');
    public model_result: string = JSON.stringify(this.JSONData);

    public ngOnInit() {
        this.user = this.JSONData;
    }
    onChange(args) {
        this.JSONData.selectedDate = args.value;
        this.model_result = JSON.stringify(this.JSONData);
    }
}
Copied to clipboard
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
//Syncfusion ej2-angular-calendars module
import { DatePickerModule } from '@syncfusion/ej2-angular-calendars';
import { AppComponent } from './app.component';


/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        DatePickerModule //declaration of ej2-angular-calendars module into NgModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }
Copied to clipboard
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);
Copied to clipboard
#container {
    visibility: hidden;
}

#loader {
  color: #008cff;
  height: 40px;
  width: 30%;
  position: absolute;
  top: 45%;
  left: 45%;
}

#element {
    display: block;
    height: 350px;
}

#wrapper {
    width: 650px;
    margin: 0 auto;
}
#calendar {
display: inline-block;
}
.valuestring{
display: inline-block;
background:#f3f3f3;
border:1px solid #c6c4c43f;
padding:10px;
}
.valuestring{
    float:right;
}