【问题标题】:Dynamically add and remove class from the page angular 7从页面角度动态添加和删除类 7
【发布时间】:2019-08-21 16:51:52
【问题描述】:

我正在使用 Angular 7,我想添加和删除动态添加的类

我有返回数字的 api。

我想要做的是在数字更高/更低时突出显示列框

较高的应用.changeGreen和较低的应用.changeRed有2个不同的类

问题是当有更高的数字并且已经应用​​了类时,css 没有影响

即如果.changeGreen 已经应用并且数量增加了,那么.changeGreen 类必须生效并突出显示框

组件文件:

getCounter() {
        const endpoint1 = 'http://localhost:8080/counter';

        this.http.get<number>(endpoint1)
            .subscribe(data => {
                if (data) {
                    if (this.test1.subs < data) {
                        this.test1['subs'] = data
                        this.test1['class'] = 'changeGreen'
                    } else if (this.test1.subs > data) {
                        this.test1['subs'] = data
                        this.test1['class'] = 'changeRed'
                    } else {
                        this.test1['subs'] = data
                        this.test1['class'] = ''
                    }

                    console.log(this.test1);

                }
                setTimeout(() => { this.getCounter(); }, 2000);
            });
    }

HTML 文件:

    <div class="row" style="font-size: 25px;color: black;">
            <div class="col-md-3" [ngClass]="test1.class">
                <div class="row">
                    <div class="col-md-5">
                        01. <img src="">
                    </div>
                    <div class="col-md-7">
                        Name <br>
                        <ng2-odometer [number]="test1.subs" [config]="{}"></ng2-odometer>
                    </div>
                </div>
</div>
            </div>

CSS 文件:

@keyframes fadeInOutGreen {
    0% {
        background-color: white;
    }

    45% {
        background-color: rgba(80, 240, 16, 0.7);
    }

    100% {
        background-color: white;
    }
}

@keyframes fadeInOutRed {
    0% {
        background-color: white;
    }

    45% {
        background-color: rgba(240, 15, 15, 0.7);
    }

    100% {
        background-color: white;
    }
}

.changeGreen {  
    animation-name: fadeInOutGreen;
    animation-delay: 0.2s;
    animation-duration: 1.2s;
}

.changeRed {  
    animation-name: fadeInOutRed;
    animation-delay: 0.2s;
    animation-duration: 1.2s;
}

【问题讨论】:

    标签: javascript css typescript angular7 angular-httpclient


    【解决方案1】:

    所以,如果我理解正确,问题是当类名.changeGreen 已经存在,并返回一个新的更高的数字时,类应该保持不变,但您希望显示类的效果吗?

    如果是这种情况,您可以尝试在每次调用开始时清空该类,然后根据数量从头开始应用它。我能想到的另一种方法是检查该类是否已经存在,然后在再次添加之前将其删除。

    如果您可以提供从端点返回的 json,也许我们可以重现该问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多