【问题标题】:Setup ngmodel value of ng2-datepicker and also make it by not editable by keyboard设置 ng2-datepicker 的 ngmodel 值,并使其无法通过键盘编辑
【发布时间】:2017-10-10 16:44:33
【问题描述】:

我在项目中使用 ng2-datepicker。这是我正在使用的代码。

<ng2-datepicker class="form-control" required [options]="{format:'MMM DD YYYY'}" [(ngModel)]="User.StartDate" name="StartDate"                                #StartDate="ngModel"></ng2-datepicker>

我被困住了

  1. 无法通过键盘使其不可编辑。

  2. 根据我的需求模型 User.StartDate 只需要绑定日期字符串。但它与数据对象绑定,例如 {day:"12",formatted:"May 12 2017",momentObject:"2017-05-11T18:30:00.000Z",month:"05",year:"2017" }。有没有办法只保存这个 ng2-datepicker 中的日期字符串。

【问题讨论】:

  • 你有同样的 plunker 吗?
  • @Rahul Singh:- 我没有过节
  • 您需要在保存数据之前使用 User.StartDate.formatted。

标签: angular date typescript momentjs ng2-datepicker


【解决方案1】:

在组件中你可以设置格式选项

在这里排序示例:

import { DatePickerOptions, DateModel } from 'ng2-datepicker';

export class Component implements OnInit {

    public options: DatePickerOptions;

    ngOnInit() {
        this.options =  {
           format: "MM-DD-YYYY",
        };
        //You should initialize date attribute like
        this.user.StartDate = {formatted: 'MM-DD-YYYY'}; // It will work as placeholder/default value;

        // If you want blank on init 
        //this.user.StartDate = {formatted: ''};
    }
    //before save data
    save() {
       this.user.StartDate = this.user.StartDate.formatted;
    }

    //To make it non-editable by a keyboard, but allow Tab and Shift+Tab key
    eventHandler(event)
    {
        if(event.keyCode == 9) {
            if(event.shiftKey)
            {
                return true;
            }
            return true;
        }
        else {
            return false;
        }
    }
}

在模板文件中:

<ng2-datepicker name="StartDate" [options]="options" [(ngModel)]="user.StartDate" (keydown)="eventHandler($event)"></ng2-datepicker>

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多