Difference between [ngClass] vs [class] binding

前端 未结 4 2174
谎友^
谎友^ 2020-11-27 17:12

What is the difference in Angular 2 between the following snippets:

4条回答
  •  忘掉有多难
    2020-11-27 17:22

    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).

    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).

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

    or

    export class AppComponent {
        isDelightful: boolean = true;
        isGlitter:  boolean = true;
    
        get sparkleGlitter()
        {
            let classes = {
                extra-sparkle: this.isDelightful,
                extra-glitter: this.isGlitter
            };
            return classes;
        }
    }
    
    

    For ngClass ,you can have conditional ternary operators too.

提交回复
热议问题