2017-03-08 59 views
3

使用Angular 2,我有一个名为“example”的参数,它是一个Date对象。在模板中,我想用日期管道格式化“example”。就像这样:Angular 2反应形式 - 管道FormControl的值

<input type="text" [value]="example | date:'shortTime'"> 
// 9:00 AM 

但是,我需要使用Angular的反应形式。 FormControls先例,因此formControlName将覆盖value指令中的任何内容。

<input type="text" formControlName="example"> 
// Wed Mar 08 2017 09:00:00 GMT-0700 (MST) 

<input type="text" formControlName="example" [value]="example | date:'shortTime'"> 
// Wed Mar 08 2017 09:00:00 GMT-0700 (MST) 

formControlName指令将不接受管道。如何在反应形式的模板中格式化Date对象?

伪代码:

@Component({ 
    template: ` 
     <form [formGroup]="formGroup"> 
      Example: <input type="text" formControlName="example"> 
     </form> 
    ` 
}) 

export class ExampleComponent implements OnInit { 
    public formGroup: FormGroup; 
    public example: Date = new Date(); 

    public ngOnInit() { 
     this.formGroup = new FormGroup({ 
      example: new FormControl(this.example) 
     }); 
    } 
} 

回答

0

为什么你不直接格式化日期?像:

this.formGroup = new FormGroup({ 
     example: [new Date().toISOString()] 
    }); 
0

这里我们可以依靠JS。你想用shortTime作为你管,所以输出可能是......

10:50 PM 

所以,当你指定的日期值,使用:

this.formGroup = new FormGroup({ 
    example: new FormControl(new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})) 
}); 

...你会得到时间显示为你的愿望:)

这里的进一步阅读Date.prototype.toLocaleTimeString()万一你有兴趣!

+4

当值更改时,它如何保持显示格式化值? – FlavorScape