jmilloy jmilloy - 3 months ago 30
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.
</video>


I also tried just including a string of attributes, which gives me an
InvalidCharacterError
because
'{{' 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
src
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
InvalidCharacterError
? I'm guessing here. So how can I get that expression to bind to the
video
element?

Note that (as far as I understand)
controls
,
autoplay
, 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
controls
attribute:

<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
controls
attribute, in a Angular 2 template?

Answer

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.
</video>

You can have more info here