How to add CSS Programmatically Angular?

Article by: Manish Methani

Last Updated: September 13, 2021 at 2:04pm IST
7 min 35 sec

Table of Contents:

Final Output

Angular 16, the latest iteration of the popular web framework, provides a robust foundation for building modern and dynamic web applications. One of the key aspects of web development is styling, and while Angular Material offers a wealth of pre-designed components, there are scenarios where you might want to add CSS programmatically to create a unique and user-friendly experience. In this article, we'll explore how to add CSS programmatically in Angular 16, using a login box example with Angular Material, and we'll ensure the UI is properly styled for an exceptional user experience.

Prerequisites

Before we dive into the code, make sure you have Angular 16 and Angular Material installed in your project. You can set up a new project using the Angular CLI:

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

 

Setting Up Angular Material Login Box

For our example, we'll create a simple login box component using Angular Material. Here's how you can set it up.

1. Generate a Dynamic Styling Component:

Use the Angular CLI to generate a new component for the login box:

ng generate component dynamic-styling

2. Update the HTML Template:

Open the dynamic-styling.component.html file and add the following code for the login box:

In this HTML template, we have a Material card containing form fields for the username and password, as well as a login button. The [ngStyle] directive will allow us to apply dynamic styles to the login container.

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

3. Define the CSS Styles:

Open the dynamic-styling.component.css file and define the initial CSS styles for the login container:

.login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background-color: #f0f0f0;
  }
  
  .full-width {
    width: 100%;
  }
  .dark-mode {
    background-color: #000; /* Black background for dark mode */
    color: #FFF; /* White text for dark mode */
  }
  
  .light-mode {
    background-color: #FFF; /* White background for light mode */
    color: #000; /* Black text for light mode */
  }
  

These styles center the login box vertically and horizontally on the page and provide some initial styling to the form fields.

Adding Dynamic Styles Programmatically

Now, let's add the ability to change the login box's style dynamically by clicking a button. We'll create a function in the component that updates the loginStyles property, and we'll bind this property to the [ngStyle] directive.

4. Update the Component Class:

Open the dynamic-styling.component.ts file and update it as follows:

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 component class:

  • We initialize the loginStyles object with the default styles for the login container.
  • We create a toggleStyles method that changes the loginStyles object when called. This simulates a button click to toggle the styles.
  1. Add a Button to Dark Mode/Light Styles: Open the login.component.html file and add a button to trigger the style toggle:
    <button class="btn bg-primary text-white" color="accent" (click)="toggleStyles()">{{buttonText}}</button>

Now, when you click the button, the CSS properties for the login container will change dynamically to light mode and dark mode.

We set the text of a button {{buttonText}} dynamically, when user click on a button.

Final Output

FAQ

1. What is the need to add CSS programmatically in Angular?

Adding CSS programmatically in Angular can be necessary for dynamic styling and theming of your application. It allows you to change the look and feel of your application based on user interactions, preferences, or application states. This dynamic approach to styling can enhance user experience and provide a more interactive and engaging web application.

2. How to load CSS dynamically in Angular 16 ?

In Angular, you can load CSS dynamically using the Renderer2 service. This service allows you to manipulate the DOM and apply or remove styles dynamically. You can use methods like `renderer.setStyle()` to set CSS properties for specific elements, enabling you to change styles based on user actions or other triggers.

3. What are some practical use cases for programmatically adding CSS in Angular?

There are several practical scenarios for adding CSS programmatically in Angular. These include implementing dynamic theming, creating responsive designs, customizing user interface elements based on user preferences, and handling state-specific styling. It is a powerful technique to enhance the visual aspects of your Angular applications.

4. Are there any best practices to follow when adding CSS programmatically in Angular?

Yes, there are best practices to consider when adding CSS programmatically in Angular. It is important to maintain a structured and organized approach to your dynamic styles. Use consistent class names or style selectors, avoid inline styles whenever possible, and document your styling logic for better code maintainability. Additionally, consider performance implications, especially when applying styles frequently.

5. Can adding CSS programmatically impact performance in Angular applications?

Yes, adding CSS programmatically can impact performance in Angular applications if not used judiciously. Frequent changes to styles, especially on a large scale, can lead to increased reflows and repaints, affecting performance. It is essential to optimize your dynamic styling code, consider using Angulars change detection strategy, and apply styles strategically to minimize performance bottlenecks.

6. What is dynamic CSS in Angular 16?

Dynamic CSS in Angular 16 refers to the ability to update and modify the styles of your web application in real-time, often in response to user interactions, application states, or other triggers. It allows you to create responsive and interactive user interfaces by changing the appearance of elements on the fly.

Explore Tech Guide:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com