Search code examples
angular

new Date with @let syntax


Using angular 18.1. I write in template:

@let formattedDate = new Date(ISODateString);

and I get an error:

Parser Error: Unexpected token 'Date' at column 5 in [new Date(ISODateString)]

How to make an instance of a date in template using @let?


Solution

  • In Angular templates, you can’t directly use JavaScript expressions like new Date() within the @let syntax. Instead, you should handle the date creation in your component class and then pass the formatted date to the template.

    1. In your component class

     export class YourComponent {
      formattedDate: Date;
    
      constructor() {
        this.formattedDate = new Date('2024-09-15T21:03:45Z'); // Replace with your ISO date string
      }
    }
    

    2. In your template:

    <p>{{ formattedDate | date: 'short' }}</p>
    

    You can find the detailed documentation for Angular's DataPipe here