Angular's ngClass directive failed to be applied correctly

I am currently experimenting with the use of [ngClass] in Angular and it appears that it is not being applied as expected. Interestingly, [ngStyle] for similar CSS styles is working without any issues. What could I be doing wrong in this scenario? There are no errors appearing in the console when I check. However, upon inspecting the dev tools, I can see that the classes are indeed being added to the element but they are not reflected in the browser view. I have attempted various options including 'class', '[class]', '[ngClass]', and 'ngClass'. Furthermore, I have also tried using both className and ngClass.

Please refer to the attached Plunker for more information:

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() { }

}

Answer №1

There seems to be an issue with your css styling.

Please make the following replacement:

 .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;
            }
            `
        ]
    })

Check out the updated code on Plunker here.

Answer №2

I am currently working on a project that I believe will be very helpful for you.

Include this code in your HTML file:

<section>
      <h2 [ngClass]='{"active":true}'>Greetings, {{name}}!</h2>
    </section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Customize Your Form Labels with Bootstrap: Changing Label Color in Forms

I am completely new to using bootstrap, particularly bootstrap 3. The goal I have is to change the color of labels such as "Name", "Email Address", "Phone Number" and "Message" from dark grey to white in the design shown below. https://i.sstatic.net/yDTto ...

Generating tables with ngFor in Angular 2

Is it possible to generate a table in Angular 2 with a dynamic number of columns by utilizing a loop based on the specified number? Specifically, how can we create a table without a fixed number of columns? ...

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

Creating dynamic visual effects for text on image with animation

I have created an animation where an image transitions from black and white to colored upon hover, accompanied by overlay text. However, when hovering over the text, the image reverts back to black and white. How can I ensure that the image stays in color ...

The issue of centering not working with a specified width under the CSS rule `margin: 0 auto

As I was creating sections for a mini "about me" page, I encountered an issue with setting margins in all divs (this one is the most important). Despite specifying widths and heights, I couldn't get margin: 0 auto; to work. body { background: #aaa; ...

Construct the output directory according to the specific environment

I'm exploring the process of constructing and launching an Angular 2 project using angular cli with variables specified in my environment typescript files. For instance, within my angular-cli.json file, there is a dev environment linked to "environme ...

Utilizing Ajax data for CSS manipulation to display a live preview populated with form inputs

I am faced with a challenge involving a form containing approximately 80 input fields of type text and select. Each input field pertains to CSS values, and I aim to display a preview showcasing the new values (onChange any input value) in the form without ...

Angular is intercepting HTTP subscriptions without finalizing them

Within my code, I have a system in place where an interceptor is triggered to check for HTTP responses with the status code 401. If this code is detected, it initiates a request for a refresh-token by calling the method refreshToken(), before retrying the ...

What could be preventing my image from displaying in the header section?

Having trouble displaying the image I added in the header section as a logo. The code works for my online course instructor, but no luck for me. I've tried different images and links to no avail. If you would like to take a look at the codes I used, ...

Is it possible to modify the color of a mat-progress-bar based on its status?

Within my project, I have implemented a mat-table containing a mat-progress-bar within each row. <mat-cell *matCellDef="let element"> {{element.id}} - {{element.address}} <mat-progress-bar mode="determinate" [v ...

Exploring the method of subscribing to streams in Angular2

I have a streaming web-service running on localhost:8080/stream that responds whenever a new message is added to the subscribed mqtt stream. I am looking to integrate this web-service into my Angular2 app using RxJS to consume NodeJS APIs. The code snipp ...

What's the best way to position an ion-label at the top of the stack

I'm having trouble creating an input label similar to the new Google style. However, when the label moves up, it gets cut in the middle as shown here. Despite trying to adjust the margin, padding, and Z-index, none of these solutions have resolved my ...

The IntroJs step is only partially visible on the screen

Currently, I am incorporating introJS into my application and encountering an issue where one of the steps is only partially visible on the screen. Despite trying various position settings such as auto, left, right, etc., this particular item consistentl ...

What is the best way to ensure that a div appears below, rather than alongside, another one

I need help positioning my divs on the webpage. Currently, my map div is appearing next to the list instead of below it. The height of the list can vary as it is generated dynamically. I want the map div to be on the right side with the list displayed on t ...

Creating a dynamic grid design with images using the <ul><li></li></ul> HTML tags

Trying to create a responsive grid of images that adapts to changes in browser size. Is there a way to achieve this using a list? Ideally, I want the images to be evenly spaced in rows. For example, if there are three rows of four images on top and one r ...

Guide to modifying CSS properties of an individual element by manipulating class names with JavaScript

I have been searching for an answer to my question without success. I have a unique challenge where I need to change the styles of an h1 element by adding a class based on which radio button is clicked. The issue I'm facing is that when I select a dif ...

Using spyOn to fake Observable responses - a step-by-step guide

My service is set up to request JSON data through HTTP: export class TodosService { constructor(private http: HttpClient) {} getTodos(): Observable<any> { return this.http.get<any>('https://jsonplaceholder.typicode.com/todos') ...

Switch from hover effects to CSS3 animations triggered on page load

I found this code snippet on https://codepen.io/chriscoyier/pen/NWNJpdJ. Can someone help me modify it to change the counter on page load instead of hover? Also, I want the counter to stop at 100 without resetting back to 0. @property --num { syntax: ...

Error: DecimalProvider is not provided by the injector

Encountering the following error message: NullInjectorError: R3InjectorError(StudentModule)[DecimalProvider -> DecimalProvider -> DecimalProvider -> DecimalProvider]: https://i.stack.imgur.com/e8D6o.png Despite importing the DecimalPipe into the ...