Search code examples
cssangularangular-ng-class

ngClass in Angular not applied


I am trying to use [ngClass] in Angular and seems like it is not getting applied. Surprising [ngStyle] for similar css styles are working. Waht am I doing wrong here? There is no error in the console. When I do check the dev tools the classes are being applied to the tag but not in the browser view. I have tried all different options - class, [class], [ngClass], ngClass. I have also tried both className and ngClass.

Please find the plunker attached for reference:

https://plnkr.co/edit/ipMxdTzoHUl5YCPJSpLT?p=preview

@Component({
    selector: 'aboutus',
    template:`
        <span class="classone classtwo">{{vari.title}}</span>
        <br>
        <div ngClass="['classone','classtwo']">{{vari.title}}</div>
         <br>
         <div [ngClass]="['classone','classtwo']">{{vari.title}}</div>
        <br>
        <div [className]="classdef">{{vari.title}}</div>
    `,
    styles: [`
        .classone{
            font-weight: 'normal' !important;
        }
        .classtwo{
            font-size: '40px' !important;
        }
        `
    ]
})
export class AboutusComponent implements OnInit, OnDestroy {
    vari: any = {title: 'test'}
    classdef: any[] = ['classone', 'classtwo']
    constructor() { }

}

Solution

  • Issue is in your css.

    replace this

      .classtwo{
            font-size: '40px' !important;
        }
    

    to

     .classtwo{
            font-size: 40px !important;
        }
    

    //our root app component

        import {Component, NgModule, VERSION, OnInit, OnDestroy} from '@angular/core'
        import {BrowserModule} from '@angular/platform-browser'
        import {CommonModule} from '@angular/common'
        @Component({
            selector: 'my-app',
            template:`
                <span class="classone classtwo">{{vari.title}}</span>
                <br>
                <div ngClass="['classone','classtwo']">{{vari.title}}</div>
                <br>
                <div [ngClass]="['classone','classtwo']">{{vari.title}}</div>
                <br>
                <div [className]="classdef">{{vari.title}}</div>
            `,
            styles: [`
                .classone{
                    font-weight: normal !important;
                }
                .classtwo{
                    font-size: 40px !important;
                }
                `
            ]
        })
    

    https://plnkr.co/edit/acLvnOvezEFI4EXjKbVx?p=preview