What is the difference between ng-class and ng-style?
ng-style用于将javascript对象插入到style属性中,而不是css类中。
以下指令将转换为style =" color:red"
1 | ng-style="{color: 'red'}" |
ng-class指令将您的对象转换为class属性。
当isDeleted变量为true时,以下内容将转换为class =" deleted"。
1 | ng-class="{'deleted': isDeleted}" |
注意:
ng样式还有一个用例。如果要在style属性中进行插值,则应考虑使用ng-style。否则,按照文档说明,这在Internet Explorer 11之前是行不通的。
因此,不要使用样式:
1 | style="width: {{progress}}" |
使用ng样式:
1 | ng-style="{'width':progress}" |
在
1 | ng-style="{ 'background-color': person.email == selectedPerson.email ? 'lightgray' : ' '}" //background-color is a style |
1 | ng-class="{ 'has-error’: !theForm.email.$valid, 'has-success':theForm.email.$valid} |
来自官方文档:https://angular.io/api/common/NgClass
这些是使用ngClass的不同方法
...
1 2 3 | <some-element [ngClass]="['first', 'second']">...</some-element> <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some- |
元素>
1 2 3 | <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element> |
2.与ngStyle类似,您可以执行以下操作:
1 | **< some-element [ngStyle]="{'font-style': styleExp}">...</some-element>** |
-
您的styleExp可以是可以评估您所设置的属性的合法值的任何值,例如上例中的font-size
-
或者,
****
... **** -
其中objExp是一个对象,其中包含样式属性的键值对
例如{width:40,margin:'2em'}等。