I am trying to parse a date in angular client side, but when I try running client-side javascript code, I get an error of: Property 'Date' does not exist on type
. Why can't I run js code in angular HTML files?
Here is an example:
// myComponent.component.html
<code>{{Date.parse("Thursday Sep 12 2022")}}</code>
My desired result should be a div with an string of milliseconds
CodePudding user response:
There are couple of ways:
- first is to create inside class a property and use it in the template like
export class TestComponent { Date = Date }
and then inside template use it like
{{Date.parse("Thursday Sep 12 2022")}}
- second is to create a function like
export class TestComponent { convertDate(data: string): Date { return Date.parse(data); } }}
and then inside template use it like
{{convertDate("Thursday Sep 12 2022")}}
- third is to use pipes (standart ones like DatePipe) or create your own
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'customDatePipe' }) export class CustomDatePipe implements PipeTransform { transform(value: string): Date { return Date.parse(data) . } }
and then inside template use it like
{{"Thursday Sep 12 2022" | customDatePipe)}}