ng2-datepicker设置空值

时间:2018-01-09 17:52:43

标签: angular ng2-datepicker

我想要实现的是设置空日期字段。默认情况下,它使用当前日期填充字段。

我的模板文件

<ng-datepicker [(ngModel)]="empty_date" [options]="options1"></ng-datepicker>  

我的.ts文件

public options1: DatepickerOptions;
ngOnInit() {
this.options1 = {
      minYear: 2018,
      maxYear: 2100,
      displayFormat: 'DD.MM.YYYY',
      barTitleFormat: 'MMMM YYYY',
      firstCalendarDay: 1
    };
this.empty_date = {formatted: ''};
}

我还尝试在options1中使用this.empty_date = "";this.empty_date = null;displayValue: ''

如何将初始字段值设置为空?

3 个答案:

答案 0 :(得分:1)

根据此issue,只需将模型初始化为null。在他们提供的演示中,我只是从这个转变:

export class AppHomeComponent {
  date: Date;
  options: DatepickerOptions = {
    locale: enLocale
  };
  constructor() {
    this.date = new Date();
  }
}

要:

export class AppHomeComponent {
  date: Date;
  options: DatepickerOptions = {
    locale: enLocale
  };
  constructor() {
    this.date = null;
  }
}

并且工作正常:

empty input value

答案 1 :(得分:0)

我在标签<ng-datepicker>上添加了模板引用,并在组件上使用了reset()方法。

HTML: <ng-datepicker #date></ng-datepicker>

组件:

@ViewChild('date') date: ElementRef;

resetDate() {
    this.date.reset();
}

答案 2 :(得分:0)

您可以使用 ElementRef 轻松清除所选日期:

<ng-datepicker [(ngModel)]="empty_date" [options]="options1" #date1></ng-datepicker>  

<button (click)="date1.displayValue=''">Clear Date</button>

您也可以从组件中清除它:

@ViewChild('date1') date1: ElementRef;

resetDate() {
    this.date1['displayValue']='';
}