Open In App

Angular Conditional Class with *ngClass

In this article, we will see the basic implementation of the Conditional class with *ngClass in Angular, along with understanding their implementation with the help of examples.

Conditional class with *ngClass

Angular’s *ngClass directive allows us to apply CSS classes conditionally to an element. It provides a convenient way to dynamically toggle classes based on specific conditions. With *ngClass, we can bind a class name or an object to an element and specify the conditions under which the class should be applied. The directive evaluates the expressions and adds or removes the specified classes accordingly. This feature is particularly useful when you want to apply different styles or behavior to an element based on certain conditions, such as user interactions, data states, or dynamic variables. Overall, *ngClass simplifies the process of adding or removing classes dynamically, making it easier to create responsive and interactive Angular applications.



Syntax:

// String expression
<div [ngClass]="'class-name'"></div>

// Array expression
<div [ngClass]="['class1', 'class2']"></div>

// Object expression
<div [ngClass]="{ 'class1': condition1, 'class2': condition2 }"></div>

// Mixed expression
<div [ngClass]="['class1', { 'class2': condition }]"></div>

There are various aspects where the *ngClass is beneficial to implement. A few of them are described below:



<div [ngClass]="{ 'active': isActive, 'highlight': isHighlighted }"></div>
<div [ngClass]="isActive ? 'active' : 'inactive'"></div>
<div [ngClass]="['active', isHighlighted ? 'highlight' : '']"></div>
<div [ngClass]="{ 'active': isActive, 'highlight': isHighlighted }"></div>

We can also use other directives like *ngIf or *ngFor along with *ngClass to conditionally apply classes based on changing states or data conditions.

Approach 1:

In this approach, when the button is clicked, it toggles the value of the “isClicked” variable and updates the message accordingly. If “isClicked” is true, the message displays “Welcome to GFG!!!” by changing the styling of the message with the help of *ngClass; otherwise, it displays nothing. The ngClass directive is used to conditionally apply the “text-darkgreen” class to the message element based on the value of “isClicked”.

Example: This example illustrates the implementation of a Conditional class with *ngClass in Angular.




<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <h2>Geeks For Geeks</h2>
            <button class="btn btn-primary"
                    (click)="getMessage()">
                  Click Me
              </button>
            <b>
                <h3 class="display" 
                    [ngClass]="{'text-darkgreen':  isClicked}">
                    {{message}}
                </h3>
            </b>
        </div>
    </div>
</div>




h2 {
    color: darkgreen;
}
  
.text-darkgreen {
    color: white;
    font-size: medium;
    width: 350px;
    padding: 20px;
    background: green;
}




import { Component } from '@angular/core';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    message: string = '';
    isClicked = false;
    getMessage() {
        this.isClicked = !this.isClicked;
        if (this.isClicked) {
            this.message = 'Welcome to GFG!!!';
        } else {
            this.message = '';
        }
    }
}

Output:

Approach 2:

In this approach, It contains a user interface with three buttons: “Toggle Success,” “Toggle Error,” and “Toggle Warning.” When a button is clicked, it triggers a corresponding function that changes the styling of the message that has been displayed accordingly with the help of *ngClass. The message is then displayed in an h3 element with a CSS class based on the active state. This allows for toggling between success, error, and warning messages dynamically.

Example: In this example, we are implementing the Conditional class with *ngClass in Angular, where the 3 toggle buttons are added that will render the message dynamically depending on the type of action.




<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <h2>Welcome to GFG!!!</h2><br>
            <button class="btn btn-success"
                    (click)="Success()">
                  Toggle Success
              </button>  
            <button class="btn btn-danger" 
                    (click)="Error()">
                  Toggle Error
              </button
            <button class="btn btn-warning" 
                    (click)="Warning()">
                  Toggle Warning
              </button
            <h3 class="display" 
                [ngClass]="{ 'Success': isSuccess, 
                             'Error': isError ,  
                             'Warning':isWarning}">
                {{message}}
            </h3>
        </div>
    </div>
</div>




h2 {
    color: darkgreen;
}
  
.Success {
    color: black;
    font-size: medium;
    width: 350px;
    padding: 20px;
    background: lightgreen;
}
  
.Error {
    color: black;
    font-size: medium;
    width: 350px;
    padding: 20px;
    background: red;
}
  
.Warning {
    color: black;
    font-size: medium;
    width: 350px;
    padding: 20px;
    background: yellow;
}




import { Component } from '@angular/core';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    isSuccess: boolean = false;
    isError: boolean = false;
    isWarning: boolean = false;
    message: string = '';
  
    Success() {
        this.isSuccess = true;
        this.isError = false;
        this.isWarning = false;
        this.message = 'Success Clicked!';
    }
  
    Error() {
        this.isError = true;
        this.isSuccess = false;
        this.isWarning = false;
        this.message = 'Danger Clicked!!';
    }
  
    Warning() {
        this.isWarning = true;
        this.isError = false;
        this.isSuccess = false;
        this.message = 'Warning Clicked!!';
    }
}

Output:


Article Tags :