【问题标题】:How to set date default value for reactive form in Angular 6?如何在Angular 6中为反应形式设置日期默认值?
【发布时间】:2019-02-14 23:13:52
【问题描述】:

我有日期过滤器的表单,我尝试为日期输入的开始日期和结束日期设置默认值。

<form [formGroup]="filter" (ngSubmit)="applyFilter()">
<mat-form-field>
    <input matInput [matDatepicker]="start" formControlName="start" placeholder="Начальная дата">
    <mat-datepicker-toggle matSuffix [for]="start"></mat-datepicker-toggle>
    <mat-datepicker #start></mat-datepicker>
</mat-form-field>
<mat-form-field>
    <input matInput [matDatepicker]="end" formControlName="end" placeholder="Конечная дата">
    <mat-datepicker-toggle matSuffix [for]="end"></mat-datepicker-toggle>
    <mat-datepicker #end></mat-datepicker>
</mat-form-field>

还有TS部分

refreshFilter() {
  const now = new Date();
  const monthAgo = new Date().setMonth(now.getMonth() - 1).toString();
  console.log(monthAgo)
  console.log(now)
  this.filter = new FormGroup({
  start: new FormControl(monthAgo, []),
  end: new FormControl(now, [])
  });

}

我一个月前的console.log()1533908066234,但对于新日期是Mon Sep 10 2018 16:34:26 GMT+0300,并且时间戳表单输入不起作用。如何将正确的月份前日期格式设置为FormControl

【问题讨论】:

  • 为什么不给默认值now.getMonth() + 1??

标签: javascript angular timestamp angular-forms


【解决方案1】:

我按照以下步骤操作,它按预期工作:

  • 使用 CLI 创建了一个新的 Angular 6 应用并将 Angular 材料添加到项目中
  • 在 app.module.ts 中导入 FormsModule 和 ReactiveFormsModule
  • 复制了与您在 app.component.html 中提供的完全相同的 html 标记
  • 在 app.component.ts 中添加以下代码

    从'@angular/core'导入{组件,OnInit}; 从“@angular/forms”导入 {FormControl, FormGroup}; @零件({ 选择器:'应用程序根', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) 导出类 AppComponent 实现 OnInit { 过滤器:表单组 ngOnInit() {
    let now = new Date();
    let monthAgo = new Date();
    monthAgo.setMonth(now.getMonth() - 1);
    
    this.filter = new FormGroup({
      start: new FormControl(monthAgo, []),
      end: new FormControl(now, [])
      });
    
    } }

希望这会有所帮助。

【讨论】:

  • 这个构造是我第一次尝试它的返回时间戳和角度崩溃。
【解决方案2】:

我找到了解决办法:

const now = new Date();
const monthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate(), now.getHours());
this.filter = new FormGroup({
    start: new FormControl(monthAgo , []),
    end: new FormControl(now, [])
});

我将日期从时间戳转换为字符串格式。就是这样。

如果有人知道如何更优雅地重写它,我将不胜感激。

【讨论】:

    【解决方案3】:

    如果你想在 Angular 中格式化日期,你可以使用 DatePipe 尝试使用管道格式化。 这允许您根据区域设置规则格式化日期值。 如果您需要有关此的更多信息,也可以在此处查看: https://angular.io/api/common/DatePipe

    这个月也要这样做Ago.toLocaleDateString()

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2022-10-12
      • 1970-01-01
      • 2020-04-11
      • 2019-01-06
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      相关资源
      最近更新 更多