Error in Angular: Template parse errors: Can't bind to 'datetime' since it isn't a known property of 'time'

Viewed 4672

I want to add attribute datetime to time element in Angular:

<time 
class="updated" 
[datetime]="post.modified_gmt">
{{ post.modified_gmt | date: 'short'}}
</time>

But get next error:

Error: Template parse errors: Can't bind to 'datetime' since it isn't a known property of 'time'. (" class="entry-date published">{{ post.date_gmt | date: 'short'}}

What the solution? Thanks for any help

3 Answers

correct the lowercase [dateTime].

<time 
  class="updated" 
  [dateTime]="post.modified_gmt">

{{ post.modified_gmt | date: 'short'}}

</time>

Have try.

You are using template binding syntax on a non-component element.

When you write [datetime]="..." it tells Angular to bind the expression to an @Input() named datetime, but the <time> tag is not part of any component or directive.

You have to use attribute syntax if you want Angular to assign the value to the element's attributes.

<time class="updated" [attr.datetime]="post.modified_gmt">{{ post.modified_gmt | date: 'short'}}</time>

Normally, you can assign expressions to attributes using {{ }} syntax. Such as <time datetime="{{post.modified_gmt}}"></time>, but this only works if Angular has the attribute in it's whitelist of supported HTML elements and attributes. It appears datetime is not supported.

You can suppress the error message by adding NO_ERRORS_SCHEMA to your @NgModule() but this only hides the error. The expression will still not set the datetime attribute.

There is a way to add your own custom schemas using CUSTOM_ELEMENTS_SCHEMA and tell Angular to support the datetime attribute, but I don't know how it works and don't think it's worth it. Just use [attr.datetime] instead.

Declare datetime as @Input() datetime; inside component for time as below :

import { Component, Input } from '@angular/core';

@Component({
  selector: 'time',
  template: `your template goes here`
})
export class TimeComponent {
  @Input() datetime: any;
}
Related