Google News
logo
Angular - Interview Questions
How to write dynamic CSS file in latest Angular?
In the latest version of Angular, you can write dynamic CSS styles by using the Angular styling system, which includes features such as component-level styles, template-level styles, and dynamic styles.
 
Component-level styles : You can add styles to a component by creating a styles property in the @Component decorator and specifying an array of CSS files or a string of CSS code. These styles will only be applied to the component they are associated with.
 
Template-level styles : You can add styles directly to a template by using the "style" or "styleUrls" properties in the template tag.
 
Dynamic styles : You can use Angular's template expressions and template statements to create dynamic styles. For example, you can use ngStyle and ngClass directives to bind styles and classes to a component based on conditionals.
 
It is recommended to use the component-level styles when possible, as they provide better performance and a clear structure.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngStyle]="{'color': myColor}">Hello World!</div>
  `,
  styles: [`
    div {
      font-size: 20px;
    }
  `]
})
export class AppComponent {
  myColor = 'blue';
}
In this example, the color of the "div" element will change to blue, by using ngStyle.
Advertisement