【问题标题】:Angular 2 - *ngFor with conditional classAngular 2 - 带有条件类的 *ngFor
【发布时间】:2016-10-25 08:02:48
【问题描述】:

我正在为一个组件使用 Angular2 和引导程序。 如果来自 *ngFor 循环的测试的属性“2”等于名为 newTest 的导入变量,我正在尝试向我的 tr-tag 添加一个类。 但它没有添加类。

这是我的组件:

loadTest() {
      this.testService.getTests()
         .then((data) => {
            this.tests = data
         })
   }

ngOnInit() {
      this.loadTest();
   }

表格显示正确,但类不存在。

不过,条件肯定是满足的。

这是我的html:

<div class="table-responsive">
    <table class="table table-hover table-reflow">
        <thead>
            <tr>
                <th>1</th>
                <th>2</th>
                <th>3</th>
                <th>4</th>
                <th>5</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let test of tests" [class.newDevice]="test.2 === this.newTest" [attr.class]="test.1" >
                <th>{{test.1}}</th>
                <th>{{test.2}}</th>
                <th>{{test.3}}</th>
                <th>{{test.4}}</th>
                <th>{{test.5}}</th>
            </tr>
        </tbody>
    </table>
</div>

我做错了什么吗? 我也尝试过用 jquery 实现同样的效果:

    loadTest() {
          this.testService.getTests()
             .then((data) => {
                this.tests = data
    if (NewTest.length !== undefined) {
                   let index = this.tests.findIndex((e) => { return e.2 === NewTest })
                   let test = this.tests[index].id
                   jQuery(test).addClass("newDevice");
                }
           })
       )

【问题讨论】:

  • 为什么你有[class.newDevice][attr.class]?这两个不是互相覆盖吗?
  • AFAIK attr.class 应该避免(例如在 Safari 移动版中引起问题)。请改用[ngClass]
  • 你能试试这个吗:[ngClass]="{ 'newDevice': test.2 == newTest }"?
  • @Martin,是的,你在正确的地方,他们确实是。实际上,[attr.class] 应该是 [attr.id],因为我在使用 jQuery 测试后忘记更改它。现在可以了。
  • @Günter Zöchbauer 我试过用 id="test.1" 代替 [attr.id]="test.1",但没有用。

标签: angular typescript angular2-template


【解决方案1】:

[class.newDevice][attr.class] 相互覆盖。

【讨论】:

    猜你喜欢
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 2017-09-20
    • 2018-03-02
    相关资源
    最近更新 更多