How to Set Styles Dynamically in Angular 16?

Article by: Manish Methani

Last Updated: September 13, 2021 at 10:04am IST
8 min 12 sec

Table of Contents:

Final Output

As a web developer, you often encounter situations where you need to change the style of elements dynamically based on user interactions or application state. Angular, a popular JavaScript framework, offers a convenient way to set styles dynamically using Angular's built-in tools. In this article, we will create a dynamic login box in Angular and demonstrate how to change its style dynamically.

Prerequisites

Before we start, make sure you have the following prerequisites:

  1. Basic knowledge of Angular.
  2. Angular CLI installed on your system.

Let's begin!

Step 1: Create an Angular Project

If you haven't already created an Angular project, open your terminal and run the following command to create a new one:

sudo npm install -g @angular/cli
sudo ng new dynamic-css-demo
cd dynamic-css-demo
ng add @angular/material
npm install

Step 2: Create a Component

Next, let's generate a new component for our dynamic login box. In your terminal, run:

ng generate component dynamic-styling

This will create a dynamic-styling component and add the necessary files.

Step 3: Design the Login Box

Open the dynamic-styling.component.html file, which is located in the src/app/dynamic-styling folder. Replace the existing content with the following HTML structure for the login box:

    <div class="login-container" [ngStyle]="loginStyles">
      <button class="btn bg-primary text-white" color="accent" (click)="toggleStyles()">{{buttonText}}</button>
    
      <mat-card>
        <h2>Login</h2>
        <mat-card-content>
          <mat-form-field class="full-width">
            <input matInput placeholder="Username" >
          </mat-form-field>
          <mat-form-field class="full-width">
            <input matInput type="password" placeholder="Password">
          </mat-form-field>
          <button class="btn bg-primary text-white" color="primary">Login</button>
        </mat-card-content>
      </mat-card>
    </div>
    

This HTML structure defines a login box with dynamic styles and a button to toggle those styles.

Step 4: Define the Component Logic

Now, let's add the component logic to dynamically change the styles of our login box. Open the dynamic-styling.component.ts file, and replace its content with the following code:

import { Component, Renderer2, ElementRef } from '@angular/core';

@Component({
  selector: 'app-dynamic-styling',
  templateUrl: './dynamic-styling.component.html',
  styleUrls: ['./dynamic-styling.component.css']
})
export class DynamicStylingComponent {
  buttonText = 'Dark Mode';

  constructor(private renderer: Renderer2, private el: ElementRef) {}
  ngOnInit() {
  }
  
  loginStyles: { [key: string]: string } = {
    'background-color': 'black',
    'border': '2px solid blue',
    'color': 'white',
    'margin':'30%',
    'margin-top': '10%',
    'height': '30%',
    'border-radius': '20px'
  };

  toggleStyles() {
    if (this.loginStyles['background-color'] === 'black') {
      this.loginStyles['background-color'] = 'white';
      this.loginStyles['border'] = '2px solid black';
      this.loginStyles['color'] = 'black';
      this.buttonText = 'Light Mode'; // Change the button text to "Light Mode"

    } else {
      this.loginStyles['background-color'] = 'black';
      this.loginStyles['border'] = '2px solid blue';
      this.loginStyles['color'] = 'white';
      this.buttonText = 'Dark Mode'; // Change the button text to "Light Mode"

    }
  }

  
}

In this code, we define the initial styles for our login box and the text of the toggle button. The toggleStyles function is called when the button is clicked, and it toggles the styles and button text between "Dark Mode" and "Light Mode."

Step 5: Use the Component

Finally, let's use our DynamicStylingComponent in the main application. Open the src/app/app.component.html file, and add the following line to include the app-dynamic-styling component:

<app-login-box></app-login-box>

Step 6: Run the Application

Save your changes and return to your terminal. Run the following command to start the Angular development server:

ng serve

Visit http://localhost:4200/ in your web browser to see the dynamic login box in action. You can click the "Dark Mode" button to toggle the styles.

Final Output

Congratulations! You've successfully created a dynamic login box in Angular and learned how to set styles dynamically. This is just the beginning of what you can achieve with Angular's powerful features. Explore further and build amazing, interactive web applications.

FAQ

1. Why is it important to set styles dynamically in Angular?

Setting styles dynamically in Angular is essential for creating responsive and interactive web applications. It enables developers to adjust the appearance of elements based on user interactions, preferences, and application states. Dynamic styling enhances user experience and allows for the development of engaging, user-centric web applications.

2. How can I dynamically set styles in Angular?

In Angular, you can dynamically set styles using the Renderer2 service. This service empowers developers to manipulate the Document Object Model (DOM) and apply or remove styles on elements dynamically. Methods like `renderer.setStyle()` allow you to change CSS properties for specific elements, offering the flexibility to adapt styles based on user actions or other triggers.

3. What are some practical examples of dynamically setting styles in Angular?

Dynamically setting styles in Angular is employed in various scenarios. These include implementing dynamic theming to give users control over the applications appearance, creating responsive designs that adapt to different devices and screen sizes, customizing UI elements based on user preferences, and applying state-specific styling. It is a powerful technique to enhance the visual aspects of your Angular applications.

4. What are the recommended practices for dynamically setting styles in Angular?

Certainly, there are best practices to follow when dynamically setting styles in Angular. It is crucial to maintain a structured and organized approach to your dynamic styles. Utilize consistent class names or style selectors, refrain from using inline styles whenever possible, and document your styling logic for improved code maintainability. Additionally, consider the performance implications, especially when applying styles frequently, and optimize your dynamic styling code accordingly.

5. Does dynamically setting styles impact the performance of Angular applications?

Yes, dynamically setting styles can influence the performance of Angular applications, especially if not used judiciously. Frequent changes to styles, particularly on a large scale, can lead to increased reflows and repaints, affecting the overall performance. To mitigate performance issues, it is vital to optimize your dynamic styling code, consider Angular s change detection strategy, and strategically apply styles to minimize performance bottlenecks.

Watch Video Tutorials at Codzify YouTube Channel:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com