【问题标题】:Angular5 input with dateAngular5输入日期
【发布时间】:2018-04-16 13:56:42
【问题描述】:

我在angular5中定义了一个日期类型的输入,这样:

<input [(ngModel)]="activity.subActivitiesList[4].releaseDate" type='date'/>

当我从网页中选择一个日期并将其插入数据库时​​,一切正常。但是,当我从 db 中读取日期并将其显示在上一个字段中时,日期(在时间戳中)不会出现。你能告诉我为什么吗?

谢谢

【问题讨论】:

    标签: html date datepicker angular5


    【解决方案1】:

    添加日期格式应使用管道显示。格式可以是短日期等

    【讨论】:

    • 我以这种方式添加了管道,但没有任何变化:
    • 请看一下这个角度日期过滤器。对月/日/年使用“M/d/yy”。 w3schools.com/angular/ng_filter_date.asp 。为了在 UI 上显示使用像这样的插值 {{..display date here..}}
    【解决方案2】:
    This can be done using pipes,
    
    Template:
     <input [value]="birthDate | date:'yyyy-MM-dd' " type='date' />
     <button (click)="setBirthDate()">Set Date</button>
    
    Typescript:
    
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      birthDate = '';
    
      setBirthDate(){
        this.birthDate = '05/05/1990';
      }
    }
    
    
    **[Live Demo:][1]**
    
    
      [1]: https://stackblitz.com/edit/angular-mxvlzv
    

    【讨论】:

    • 如果我插入 type='date' 它不起作用,但如果我删除类型,它工作正常。类型会造成混淆吗?
    【解决方案3】:

    日期可以从 typescript 转换为 'yyyy-MM-dd'。检查下面的代码。

    // HTML

         <input [(ngModel)]="date" name="date" type='text' />
         <button (click)="setDate()">Set Date</button>    
    

    //打字稿

    import { Component } from '@angular/core';
    
    import { DatePipe } from '@angular/common'
    
    @Component({
        templateUrl: './test.component.html',
     })
    
     export class TestComponent {
    
         constructor(private datePipe: DatePipe){}
    
         date : any;
    
         setDate(){     
    
             this.date = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
    
         }
    
     }
    

    并在 app.module.ts 中添加“DatePipe”

    从“@angular/common”导入 { DatePipe };

    @ngModules ({

    ... 提供者:[DatePipe]

    })

    【讨论】:

    • 这是一个休息响应,所以如果它有效,管道将是最好的解决方案
    【解决方案4】:

    好的,我终于找到了问题所在。首先感谢您的回复,正确的解决方案正是使用管道但是: 1) 管道的日期格式必须与检索的日期相同; 2) 管道的日期格式不得与用户看到的相同。

    例如:在我的情况下,数据库日期格式是“yyyy-MM-dd”,但显示的日期格式是“dd/MM/yyyy”。所以管道必须设置为'yyyy-MM-dd'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      相关资源
      最近更新 更多