【问题标题】:Angular 2 Assign dynamical Class to ElementAngular 2将动态类分配给元素
【发布时间】:2017-03-22 22:12:53
【问题描述】:

我对 Angular 2 很陌生,我想为 HTML 元素分配一个类。 它应该是动态的 --> 如果另一个元素(带有 id)有一个属性,这个元素应该成为类。

这是我尝试过的代码:

<div class="panel panel-default" ngFor="let date of epgDates; let i = index">
    <div class="panel-heading" role="tab">
        <h4 class="panel-title">
            <a #aEle role="button" data-toggle="collapse" id="a-{{i}}" href="#{{i}}" aria-expanded="true"> 
                <span class="glyphicon" [class.glyphicon-minus]="aEle.getAttribute('aria-expanded')==='true'"
                    aria-hidden="true">
                </span> {{date | date: 'dd.MM.yyyy'}}
            </a>
        </h4>
    </div>
</div>

使用此代码我得到一个错误...:/ 有人可以帮我吗?

非常感谢!

【问题讨论】:

  • 预期结果是什么。 [class.glyphicon-minus] 表示您想要添加/删除类 glyphicon-minus 但我完全不清楚 "#a-{{i}}.aria-expanded='true'" 应该做什么。
  • 如果 id 为 a-{{i}}(例如 a-0)的元素的“aria-expanded”属性为真,则应添加该类。

标签: html twitter-bootstrap angular


【解决方案1】:

您不能同时使用[]{{}}。一个或另一个,但不能两者兼而有之

"true" 是返回true 的表达式时,这将设置类,否则将删除该类

[class.glyphicon-minus]="true"

这会在表达式 true 返回 true 时设置一个类 glyphicon-minus,否则会删除该类,并在第二个表达式返回 true 时设置或删除类 #a-1.aria-expanded,否则将其删除(假设 i1)。 类名可以是字符串('glyphicon-minus')或表达式('#a-' + i + '.aria-expanded'

[ngClass]="{'glyphicon-minus': true, '#a-' + i + '.aria-expanded': true}"

表达式true 和是一个文字布尔值(如图所示)或组件类的属性名称,或者是具有运算符和函数调用的更复杂的表达式。

更新

<a #aEle role="button" data-toggle="collapse" id="a-{{i}}" href="#{{i}}" aria-expanded="true">
    <span class="glyphicon" [class.glyphicon-minus]="aEle.getAttribute('aria-expanded')==='true'" aria-hidden="true"></span> 
    {{date | date: 'dd.MM.yyyy'}}
</a>

我将#aEle 模板属性添加到&lt;a&gt; 并使用它来获取aria-expanded 属性值。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 2017-03-11
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 2019-07-22
相关资源
最近更新 更多