【问题标题】:How to have a 2-way formatter for input-field?如何为输入字段提供 2 路格式化程序?
【发布时间】:2019-10-18 09:57:37
【问题描述】:

我喜欢将 Date 双向绑定到输入控件。

public dtm : Date;
...
this.dtm = new Date ();

...

<input type="text" placeholder="DD.MM.YYYY" [(ngModel)]="dtm"/>

如果我这样做了,那么输入将以其标准格式显示日期。

例如2019 年 10 月 19 日星期六 11:53:00 GMT+0200 (CEST)

是否可以为特殊格式(例如 DD.MM.YYYY)提供一种 2-way (!) 格式化程序?

我喜欢在代码中有一个 Date 实例,但也有一个格式化输出 (Date -> DD.MM.YYYY) 和一个输入解析 (DD.MM.YYYY -> Date)。

编辑 至少我想要一个 2 路绑定和一个输出格式化程序。但我不确定如何使用 [(ngModel)] 和日期管道。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    在我看来,我们不能直接使用 2-way 绑定。这是一个解决方法

    <input type="date" [ngModel]="dtm | date:'yyyy-MM-dd'" (input)="dtm=$event.target.valueAsDate" />
    

    <input type="text" [ngModel]="dtm1 | date:'shortDate'" (ngModelChange)="dtm1=parseDate($event)" /> 
    

    parseDate 是一个将字符串解析为日期的函数。

    如果 Angular DatePipe 不能满足您的需求,您可以根据需要定义自定义 DatePipe

    这是一个简单的StackBlitz

    【讨论】:

      【解决方案2】:

      如果我理解正确,那么您可以在 TS 中使用 DatePipe 根据您的要求来格式化日期:

      进口:

      import { DatePipe } from "@angular/common"
      

      HTML:

      <mat-form-field>
          <input matInput [matDatepicker]="dp1" [(ngModel)]="dtm" (dateInput)="change($event.target.value, $event)" placeholder="Choose a date">
          <mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
          <mat-datepicker #dp1></mat-datepicker>
      </mat-form-field>
      

      TS 代码:

      import { Component } from "@angular/core";
      import { DatePipe } from "@angular/common";
      
      @Component({
        selector: "table-filtering-example",
        styleUrls: ["table-filtering-example.css"],
        templateUrl: "table-filtering-example.html",
        providers: [DatePipe] -- Add in Providers array
      })
      export class TableFilteringExample {
        public dtm: Date;
        selectedDate: any;
      
        constructor(public datepipe: DatePipe) { --Inject here
          this.dtm = new Date();
        }
      
        change(date: string, event) {
          if (event.value != undefined) {
            this.selectedDate = this.datepipe.transform(date, "M/d/yyyy");
            console.log(this.selectedDate);
          }
        }
      }
      

      StackBlitz Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        相关资源
        最近更新 更多