【问题标题】:Angular 2 Ng style isnt removing old style when the model object changes模型对象更改时,Angular 2 Ng 样式不会删除旧样式
【发布时间】:2016-12-01 01:04:03
【问题描述】:

我在我的项目中遇到了这个问题。 如果您在 div 中将对象分配给 ngStyle,则 ngStyle 不会在对象更改时刷新旧对象的样式属性。

虽然应该刷新所有旧的对象样式,并且应该只应用新的对象样式属性。

为了显示问题,我已经在ngStyle github page 上分叉了 plunkr。

您可以在此plunkr 重现该问题。

  <div [ng-style]="selectedStyle">
 Change style of this text!
</div>


changeFirst(){
 this.selectedStyle = {"border-width": "5px", "border-style": "solid", "border-color": "black"};
}

changeSecond(){
  this.selectedStyle = {"background-color": "red"};
}

在 plunkr 中,单击第一个样式对象,它将应用,它会给 div 一个边框。然后点击第二个样式,它会给它背景颜色,但也会保留以前样式的边框。

环境-

Angular 版本:2.0.0-alpha.39

语言:TS

【问题讨论】:

  • 检查 ng 样式的源代码..我认为,它会有所不同并添加它们..而它应该刷新旧属性
  • 我很确定 ngstyle 在这里按预期工作 - 它添加到现有样式,但不会替换它。也感觉自己用错了?它应该使用样式,然后根据表达式根据需要更改它
  • @rlweb 不理解这部分 - 它应该使用样式,然后根据表达式根据需要更改它
  • 你是对的。我和班级混在一起。还早到这里,抱歉!
  • 我想过使用类,但我的应用程序需要提供动态样式..这就是我选择 ng 样式的原因..我记得同一个应用程序是使用 angular 1 制作的,它曾经可以正常工作..这个问题与应用程序的 ng 2 版本有关..谢谢

标签: angular


【解决方案1】:

这会起作用。

changeFirst(){
  this.selectedStyle = {"border":"5px solid black"}; //<----- made change here.
}

changeSecond(){
  this.selectedStyle = {"background-color": "red"};
}

【讨论】:

  • 感谢您的回答..这可能有效,但样式在我的应用程序中将是动态的..所以问题更基本..我认为问题仅在于 ng 样式
  • ng-style 没有问题。它需要正确的输入。我无法告诉您为什么它不能与单个属性一起使用的确切原因,但我的建议与您的 Angular2 版本一样有效。
【解决方案2】:
--html

<button md-button *ngFor="let mod of mappedModules;let k= index" [style.font-weight]="modStyle[k]" (click)="moduleButtonClicked(k)">{{ mod.name }}</button>

--ts
moduleButtonClicked(index: any){

    for(var i=0;i<this.modStyle.length;++i){
        if(i==index){
            this.modStyle[i]= 'bold';
        }
        else{
            this.modStyle[i]='normal';
        }
    }

}

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2016-04-27
    相关资源
    最近更新 更多