My code works this far, but now I would like the new timestamp to appear on the list when I press the button again. (example 10:01, 10:02, 10:03 etc..) Currently, it adds the same old original timestamp (for example, 10:00, 10:00, 10:00, etc., this is what I don't want).
I would also like the style rules (ngStyle & ngClass) to take effect only after the user has pressed the button 5 times.
Huge thanks in advance!
HTML
<section>
<button (click)="toogleTag()"> Push me </button>
<p *ngIf="showMe"> Some random text </p>
<div *ngFor="let click of listOfClicks">
<div [ngStyle]="{'background-color':'black'}">
<p [ngClass]="{'text-white': true}">
{{ Date1 }}
</p>
</div>
</div>
</section>
Component.ts
import { Component, OnInit } from '@angular/core';
export class DisplayDetailsComponent implements OnInit {
numberOfClicks: number = 0;
listOfClicks: any = [];
showMe:boolean=false
ngOnInit() {}
toogleTag() {
this.showMe=!this.showMe;
this.numberOfClicks ;
this.listOfClicks.push(this.numberOfClicks);
}
constructor() { }
Date1 : Date = new Date();
}
CodePudding user response:
You always print the same date because you are binding always to the same variable. You could have the list of clicks to host the date where those have been clicked.
<section>
<button (click)="toogleTag()">Push me</button>
<p *ngIf="showMe">Some random text</p>
<div *ngFor="let date of listOfClicks">
<div [ngStyle]="listOfClicks?.length >= 5 && { 'background-color': 'black' }">
<p [ngClass]="listOfClicks?.length >= 5 && { 'text-white': true }">
{{ date }}
</p>
</div>
</div>
</section>
showMe = false;
numberOfClicks = 0;
listOfClicks: Date[] = [];
toogleTag() {
this.showMe = !this.showMe;
this.numberOfClicks ;
this.listOfClicks.push(new Date());
}
Tip: I would avoid having both, ngStyle and ngClass if possible, try to group them both in one of then, like having 2 classes, having 1 class, or using the two properties.
CodePudding user response:
Here's an example: https://stackblitz.com/edit/plain-angular6-2zqzeh
I've added hh:mm:ss format so that you can test that the logic works correctly, and you can remove parts dealing with seconds if you wish.
Basicly, added a new array and method to push hh:mm:ss strings to it, while pushing Date through formatter method.
toogleTag() {
this.showMe = !this.showMe;
this.numberOfClicks ;
this.listOfClicks.push(this.numberOfClicks);
this.getTime();
}
formatTime(time) {
if (time < 10) return time = '0' time;
else return time;
}
getTime() {
let today = new Date();
let h = this.formatTime(today.getHours());
let m = this.formatTime(today.getMinutes());
let s = this.formatTime(today.getSeconds());
this.listOfTimes.push(h ':' m ':' s);
}
and template:
<div *ngFor="let time of listOfTimes">
{{ time }}
</div>
(css and other details omitted)
Also I remember your code :) (List of number of clicks (Angular))
