Angular [ngClass] vs [class

2019-01-11 10:19发布

What is the difference in Angular between the following snippets:

<div [class.extra-sparkle]="isDelightful">
<div [ngClass]="{'extra-sparkle': isDelightful}">

4条回答
神经病院院长
2楼-- · 2019-01-11 10:56

The above two lines of code is with respect to CSS class binding in Angular.There are basically 2-3 ways you can bind css class to angular components

You provide a class name with class.className between brackets in your templates and then an expression on the right that should evaluate to true or false to determine if the class should be applied.That is the below one where extra-sparkle(key) is the css class and isDelightful(value).

<div [class.extra-sparkle]="isDelightful">

When multiple classes should potentially be added, the NgClass directive comes in really handy. NgClass should receive an object with class names as keys and expressions that evaluate to true or false.extra-sparkle is the key and isDelightful is the value(boolean).

<div [ngClass]="{'extra-sparkle': isDelightful}">

Now along with extra sparkle ,you can glitter your div also.

<div [ngClass]="{'extra-sparkle': isDelightful,'extra-glitter':isGlitter}">

or

export class AppComponent {
    isDelightful: boolean = true;
    isGlitter:  boolean = true;

     sparkleGlitter()
    {
        let classes = {
            extra-sparkle: this.isDelightful,
            extra-glitter: this.isGlitter
        };
        return classes;
    }
}

<div [ngClass]='sparkleGlitter()'>

For ngClass ,you can have conditional ternary operators too.

查看更多
Fickle 薄情
3楼-- · 2019-01-11 10:56

In [ngClass] you can add one of two different classes like this:

<div [ngClass]="a === b ? 'class1' : 'class2'">
查看更多
地球回转人心会变
4楼-- · 2019-01-11 11:04

This is special Angular binding syntax

<div [class.extra-sparkle]="isDelightful">

This is part of the Angular compiler and you can't build a custom binding variant following this binding style. The only supported are [class.xxx]="...", [style.xxx]="...", and [attr.xxx]="..."

ngClass is a normal Angular directive like you can build it yourself

<div [ngClass]="{'extra-sparkle': isDelightful}">

ngClass is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example.

查看更多
虎瘦雄心在
5楼-- · 2019-01-11 11:10

Using [ngClass] you're able to apply multiple classes in a really convenient way. You can even apply a function that will return an object of classes. [class. makes you able to apply only one class (of course you can use class. a few times but it looks really bad).

查看更多
登录 后发表回答