Ways to style components in angular

There are many ways to style components in angular.  Some of them are described below

1. Using a styles property-

in the component metadata, we can put styles properties, this property contains the CSS code

import { Component } from '@angular/core';
@Component({
  selector: 'style-component',
  template: `
  <div>
    This is a text
  </div>
  `,
  styles: ['div {color:red;}']
})
export class styleComponent  {
}

2. By providing a path of the CSS file in the component metadata

in the component metadata, we can provide the path of the CSS file in the styleUrls property and then write a CSS in the separate file

import { Component } from '@angular/core';
@Component({
  selector: 'style-component',
  template: `
  <div>
    This is a text
  </div>
  `,
  styleUrls:['style.component.css']
})
export class styleComponent  {
/*
 ......
*/
}

3.Using Inline CSS -

We can also write a CSS code in the HTML template by putting the style attribute in the tag

import { Component } from '@angular/core';
@Component({
  selector: 'style-component',
  template: `
  <div style="color: red;">
    This is a text
  </div>
  `,
})
export class styleComponent  {
/*
 ......
*/
}

 

We can also add a dynamic CSS in angular

 1. Using the condition-

We can also apply conditions to the CSS in the HTML template.

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `
  <div [style.color]="str.length > 5 ? 'red':'yellow'">
    {{str}}
  </div>
  `
})
export class styleComponent  {
str = "This is a text"
}

you can see in the above example the CSS of the str changes depending on the str length. if the length is 5 or more, the text color will be red; if the length is less than 5, then the color of the text will be yellow. 

2. using ngStyle Directive -

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `
  <div [ngStyle]="{'color':fruit.color}" *ngFor="let fruit of fruit">
    {{fruit.name}}
  </div>
  `
})
export class styleComponent  {
fruit =[
  {
    'name':'Apple',
    'color':'red',
  },
  {
    'name':'Banana',
    'color':'yellow',
  }
];
}
 
In the above example, the text color changes depending on the color listed in the fruit array
 
3. Using ngClass Directive
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `
  <div [ngClass]="{'allowed':isAllowCss}">
    This is a text
  </div>
  `,
 styles:[`.allowed{
   color:red;
 } `]
})
export class styleComponent  {
isAllowCss: boolean = true;
}
In the above example, the CSS is only applied if the isAllowCss variable is true.  The many options for using style allow greater flexibility to the programmer.
 
 
 

Add comment