Anil
Anil

Reputation: 1772

How to get the date time from template into component

I am using datetime pipe to format the time and displaying in template. But I want to get the same time in my component. How to achieve this?

Here is the stackblitz : https://stackblitz.com/edit/angular-sb3ekr

I want to get the displayed date time in app.component.ts using some variable. Please tell me how to do this?

Upvotes: 0

Views: 552

Answers (2)

Anil
Anil

Reputation: 1772

I solved it using ViewChild and ElementRef, here it is what I have changed,

HTML,

<span #dtime> {{ today | date :'dd-MM-yyyy hh:mm:ss'}}</span>

Component,

today: number = Date.now();
  dateT: string = undefined;

@ViewChild("dtime", {read: ElementRef}) dtime: ElementRef;

  ngAfterViewInit(): void {
    this.dateT = this.dtime.nativeElement.textContent;
 // console.log(this.dtime.nativeElement.textContent);
  console.log(this.dateT);
  }

Upvotes: 0

Krishna Mohan
Krishna Mohan

Reputation: 1732

You can use DatePipe in your component.

var tmp = new DatePipe('en-Us').transform(this.today, 'dd:MM:yyyy hh-mm-ss');

Upvotes: 0

Related Questions