Home > Enterprise >  How to access actual text content from HTML Date input
How to access actual text content from HTML Date input

Time:09-22

I am using a native HTML Date input component like below in Angular -

 <input #dateField id="dateField" type="date">
@ViewChild("dateField") el: ElementRef;

onClick() {
  console.log(this.el.nativeElement.shadowRoot);
}

It rendered the date based on the operating system locale of the user like below -

enter image description here

However, whenever I try to access the value from this field, it always returns the value in 'yyyy-mm-dd' format.

I want to access the actual string value which is getting displayed on the UI as per user locale like '16-Sep-2021'. Is there any way to achieve this? I have tried properties such as innerHTML, textContent, innerText, outerText but none of them is returning the actual displayed value.

Also, is it possible to access the locale information in which it is showing this date value? Even if the default placeholder text -

enter image description here

I am also not able to access the shadowRoot property on this element, it always returns me null.

Also, this is not specific with Angular, even if normal Javascript it gives same result.

CodePudding user response:

There is no way to achieve what you're looking for. You can only retrieve the value in one of the following formats:

  1. value will return the date in yyyy-mm-dd.
  2. valueAsNumber will return the date in timestap
  3. valueAsDate will return the date in JavaScript Date format.

CodePudding user response:

In angular you can use,

fromDate

package to convert date into output like you wanted, here is the snippet just copy and paste at required place and you will be able to see the date format you wanted:

//add this
import { formatDate } from "@angular/common";

//format it
const format = 'dd/MM/yyyy';
const myDate = '2019-sep-16';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
console.log(formattedDate)//16/09/2019

Hope this will help :-p

  • Related