Javascript Angular 4 显示当前时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46562122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 4 display current time
提问by BOPOHOB
What is the correct (canonical) way to display current time in angular 4 change detection system?
在 angular 4 变化检测系统中显示当前时间的正确(规范)方式是什么?
The problem is as follows: current time changes constantly, each moment, by definition. But it is not detectable by Angular 4 change detection system. For this reason, in my opinion, it's necessary to explicitly call ChangeDetectorRef::detectChanges. However, in the process of calling this method, current time naturally changes its value. This leads to ExpressionChangedAfterItHasBeenCheckedError. In the following example (see live) this error appears withing a few seconds after loading the page:
问题如下:根据定义,当前时间每时每刻都在不断变化。但它无法被 Angular 4 变化检测系统检测到。出于这个原因,在我看来,有必要明确调用ChangeDetectorRef::detectChanges. 但是,在调用这个方法的过程中,当前时间自然会改变它的值。这导致ExpressionChangedAfterItHasBeenCheckedError. 在下面的例子中(参见 live)这个错误在加载页面几秒钟后出现:
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'my-app',
template: `{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />
{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />
{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />
{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />
{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />
{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />
{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />
{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}<br />{{ now }}`
})
export class AppComponent {
get now() : string { return Date(); }
constructor(cd: ChangeDetectorRef) {
setInterval(function() { cd.detectChanges(); }, 1);
}
}
回答by cyr_x
First of all you don't need to call ChangeDetectorRef.detectChanges()inside your interval, because angular is using Zone.jswhich monkey patches the browsers setInteralmethod with its own. Therefore angular is well aware of the changes happening during an interval.
首先,您不需要ChangeDetectorRef.detectChanges()在您的时间间隔内调用,因为 angular 正在使用Zone.js哪个猴子setInteral用自己的方法修补浏览器方法。因此,angular 很清楚间隔期间发生的变化。
You should set the time inside your interval like this:
您应该像这样在间隔内设置时间:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `{{ now }}`
})
export class AppComponent {
public now: Date = new Date();
constructor() {
setInterval(() => {
this.now = new Date();
}, 1);
}
}
But you shouldn't update the time on such a high rate, because it would lead to poor perfomance, because everytime the date updates angular performs a changedetection on the component tree.
但是你不应该以如此高的速度更新时间,因为它会导致性能不佳,因为每次更新日期时 angular 都会对组件树执行更改检测。
If you want to update the DOM at a very high rate, you should use runOutsideAngularfrom NgZoneand update the DOM manually using the Renderer2.
如果您想以非常高的速度更新 DOM,您应该使用runOutsideAngularfromNgZone并使用Renderer2.
For example:
例如:
@Component({
selector: 'my-counter',
template: '<span #counter></span>'
})
class CounterComponent implements OnChange {
public count: number = 0;
@ViewChild('counter')
public myCounter: ElementRef;
constructor(private zone: NgZone, private renderer: Renderer2) {
this.zone.runOutsideAngular(() => {
setInterval(() => {
this.renderer.setProperty(this.myCounter.nativeElement, 'textContent', ++this.count);
}, 1);
});
}
}
回答by mrOak
As per Angular documentation on the DatePipeLink, Date.now()can be used.
根据DatePipe链接上的 Angular 文档,Date.now()可以使用。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `{{ now | date:'HH:mm:ss'}}`
})
export class AppComponent {
now:number;
constructor() {
setInterval(() => {
this.now = Date.now();
}, 1);
}
}
回答by Oliver
Actually, you don't need any library for this simple task. If you are doing in your angular project with angular 6+ then import formatDate from the common package and pass other data. Here is a sample:
实际上,这个简单的任务不需要任何库。如果您在使用 angular 6+ 的 angular 项目中进行操作,则从公共包中导入 formatDate 并传递其他数据。这是一个示例:
import { Component } from '@angular/core';
import {formatDate } from '@angular/common';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
today= new Date();
todaysDataTime = '';
constructor() {
this.todaysDataTime = formatDate(this.today, 'dd-MM-yyyy hh:mm:ss a', 'en-US', '+0530');
}
}
Here is a stackblitz link, you can edit here: https://stackblitz.com/edit/angular-h63y8e
这是一个stackblitz链接,你可以在这里编辑:https://stackblitz.com/edit/angular-h63y8e
回答by Bruce Smile
CurrentTime: any;
constructor() {
setInterval(() => {
this.CurrentTime = new Date().getHours() + ':' + new Date().getMinutes() + ':'+ new Date().getSeconds()}, 1);
}
回答by Jinto Antony
today: number = Date.now();
constructor() {
setInterval(() => {this.today = Date.now()}, 1);
}
If you want to format this on html page, use it like this:
如果你想在 html 页面上格式化它,像这样使用它:
<p>{{today | date:'fullDate'}} {{today | date:'h:mm:ss a'}}</p>
回答by phani indra
Use arrow function.
使用箭头功能。
constructor(cd: ChangeDetectorRef){
setInterval(() => { cd.detectChanges(); }, 1);
}

