jmilloy jmilloy - 2 years ago 269
HTML Question

boolean attributes in angular 2 templates

I'd like to be able to control the video attributes with a template expression. The following template (excerpt) is giving me a template parse error

Unexpected closing tag "video"

<video {{ myVideo.controls ? 'controls' : '' }}>
<source src="{{ myVideo.src }}" type="video/mp4">
Video not supported.

I also tried just including a string of attributes, which gives me an
'{{' is not a valid attribute name

<video {{ myVideo.attributes }}>

I'm new to Angular, and I'm using Angular 2. It appears that a template expression is bound to a property, e.g. an attribute or event. So perhaps
<source src="{{ myVideo.src }}">
works because the expression is bound to the
attribute, but
<video {{ myVideo.attributes }}
does not because there isn't an attribute to bind to? So the expression isn't evaluated, which would be consistent with the
? I'm guessing here. So how can I get that expression to bind to the

Note that (as far as I understand)
, etc are boolean attributes, meaning that they have to be either included or omitted rather than assigned values. So the following might parse the template as expected but doesn't function to turn on or off the

<video controls="{{ myVideo.controls }}">

Possibly my interpretation of the problem is entirely wrong. In any case, how can I conditionally include boolean attributes, such as the video
attribute, in a Angular 2 template?

Answer Source

You are using the bind in a wrong way.

To set an attribute, just use [attr.attrName]="expression" as a did bellow:

<video [attr.controls]="myVideo.controls">
  <source [attr.src]="myVideo.src" type="video/mp4">
  Video not supported.

You can have more info here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download