【问题标题】:boolean attributes in angular 2 templatesAngular 2 模板中的布尔属性
【发布时间】:2016-08-30 18:20:18
【问题描述】:

我希望能够使用模板表达式控制视频属性。以下模板(摘录)给了我一个模板解析错误Unexpected closing tag "video"

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

我还尝试只包含一串属性,这给了我一个InvalidCharacterError,因为'{{' is not a valid attribute name

<video {{ myVideo.attributes }}>

我是 Angular 的新手,我正在使用 Angular 2。模板表达式似乎绑定到了一个属性,例如属性或事件。所以也许&lt;source src="{{ myVideo.src }}"&gt; 有效,因为表达式绑定到src 属性,但&lt;video {{ myVideo.attributes }} 没有,因为没有要绑定的属性?所以表达式没有被评估,这将与InvalidCharacterError 一致?我猜这里那么如何让该表达式绑定到video 元素呢?

请注意(据我所知)controlsautoplay 等是布尔属性,这意味着它们必须被包含或省略,而不是赋值。因此,以下可能会按预期解析模板,但无法打开或关闭 controls 属性:

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

可能我对这个问题的解释是完全错误的。无论如何,如何在 Angular 2 模板中有条件地包含布尔属性,例如视频 controls 属性?

【问题讨论】:

    标签: html templates angular


    【解决方案1】:

    您以错误的方式使用绑定。

    要设置一个属性,只需使用 [attr.attrName]="expression" 就可以了:

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

    您可以了解更多信息here

    【讨论】:

    • 第一个版本运行良好,[controls]="myVideo.controls",谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2013-09-22
    • 2011-12-26
    • 2016-09-30
    • 2017-07-04
    相关资源
    最近更新 更多