Debug School

rakesh kumar
rakesh kumar

Posted on

Angular:How to add styles to Angular Components

Reference1
Reference2
Reference3
Reference4
Reference5
Reference6
Reference7
Reference8
Reference9

Component Inline style
Component External Style
Template Inline Style using link tag
Template using style directive
Angular NgClass Directive
Angular ngStyle Directive
Class Binding in Angular

QUESTION
How to add multiple styles using Component External Style
How to specify both Component inline & Component External style together
How to add the external style sheets using the the link tag

How to add styles to Angular Components
The Angular allow us the specify the component specific styles. There are four ways you can apply style.

  1. Component Inline style
  2. Component External Style
  3. Template using link directive
  4. Template using style directive

How these styles affect the component and other components depend on the ViewEncapsulation strategy used by the component. By default, Angular uses the ViewEncapsulation.Emulated , which ensures that the component styles do not bleed out to other components. Click to find out more about View Encapsulation in Angular.

Component Inline Style
Use the styles: metadata of the @Component or @Directive to specify the CSS rules as shown below.

 @Component({
  selector: 'app-user-inline-style',
  templateUrl: './user-inline-style.component.html',
  styles: ['h1 { color:red }']
})
Enter fullscreen mode Exit fullscreen mode
@Component({
  selector: 'app-test1',
  templateUrl: './test1.component.html',
  styles: [
    `p { color:blue}`
  ],
})
Enter fullscreen mode Exit fullscreen mode
 @Component({
  selector: 'app-user-inline-style',
  template: `
  <style>
      h1 {
        color:red
      }
    </style>
    <h1>Component with inline style</h1>
  `,
  styles: [
  ]
})
Enter fullscreen mode Exit fullscreen mode

Use backtick character to enter the multi-line style.

You can add multiple styles by separating each other using a comma as shown below

styles: [
    `p { color:blue}`,
    `h1 {color:blue}`  
  ],
Enter fullscreen mode Exit fullscreen mode

Component External Style
Specify the external style sheets using the styleUrls: meta data of the @Component decorator or @directive directive.

@Component({
  selector: 'app-test2',
  templateUrl: './test2.component.html',
  styleUrls: ['./test2.component.css'],
})
Enter fullscreen mode Exit fullscreen mode

You can add multiple styles by separating each other using a comma as shown below

styleUrls: ['./test2.component.css','.another.stylesheet.css'],
Enter fullscreen mode Exit fullscreen mode

You can specify both Component inline & Component External style together as shown below

@Component({
  selector: 'app-test2',
  templateUrl: './test2.component.html',
  styles:[`p {color:yellow}`],
  styleUrls: ['./test2.component.css'],
})
Enter fullscreen mode Exit fullscreen mode
 @Component({
  selector: 'app-user-inline-style',
  templateUrl: './user-inline-style.component.html',
  styles: ['h1 { color:red }'],
  styleUrls: ['./user-inline-style.component.scss']
})
Enter fullscreen mode Exit fullscreen mode

The Angular inserts component inline style first and then inserts the component external style. Hence, component external styles takes precedence over the component inline styles.

Template Inline Style using link tag
You can add the external style sheets using the the link tag as shown below. The path must be relative to the index.html

@Component({
  selector: 'app-user-inline-style',
  template: `
    <!-- relative URL of the stylesheet -->
    <link rel="stylesheet" href="../assets/user-style.css">
    <h1>Component with inline style</h1>
  `,
  styles: [
  ]
})
Enter fullscreen mode Exit fullscreen mode
<link rel="stylesheet" href="assets/css/morestyles.css">
<p>
  test2 works!
</p>
Enter fullscreen mode Exit fullscreen mode
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

<p>
  test2 works!
</p>
Enter fullscreen mode Exit fullscreen mode

Style Priority
The styles are applied in the following order

  1. Component inline styles i e. Styles defined at @Component.styles
  2. Component External styles i.e. @Component.styleUrls
  3. Template Inline Styles using the style tag
  4. Template External Styles using the link tag

Angular NgClass Directive

The Angular ngClass Directive is an Angular Attribute Directive, which allows us to add or remove CSS classes to an HTML element. Using ngClass you can create dynamic styles in angular components by using conditional expressions

NgClass
The ngClass directive adds and removes CSS classes on an HTML element. The syntax of the ngClass is as shown below.

<element [ngClass]="expression">...</element>
Enter fullscreen mode Exit fullscreen mode

Where

element is the DOM element to which class is being applied

expression is evaluated and the resulting classes are added/removed from the element. The expression can be in various formats like string, array or an object. Let us explore all of them with example

NgClass with a String
You can use the String as expression and bind it to directly to the ngClass attribute. If you want to assign multiple classes, then separate each class with space as shown below.

<element [ngClass]="'cssClass1 cssClass2'">...</element>
Enter fullscreen mode Exit fullscreen mode

Example
Add the following classes to the app.component.css

.red { color: red; }
.size20 { font-size: 20px; }
Enter fullscreen mode Exit fullscreen mode

Add the following to the app.template.html

<div [ngClass]="'red size20'"> Red Text with Size 20px </div>
Enter fullscreen mode Exit fullscreen mode

The above example code adds the two CSS Classes red & size20 to the div element.

You can also use the ngClass without a square bracket. In that case, the expression is not evaluated but assigned directly to the class attribute. We also need to remove the double quote around the expression as shown below.

<div class="row">     
    <div ngClass='red size20'>Red Text with Size 20px </div> 
</div>
Enter fullscreen mode Exit fullscreen mode

NgClass with Array
You can achieve the same result by using an array instead of a string as shown below. The syntax for ngClass array syntax is as shown below

<element [ngClass]="['cssClass1', 'cssClass2']">...</element>
Enter fullscreen mode Exit fullscreen mode

Example
All you need to change the template as shown below

<div [ngClass]="['red','size20']">Red Text with Size 20px </div>
Enter fullscreen mode Exit fullscreen mode

NgClass with Object
You can also bind the ngClass to an object. Each property name of the object acts as a class name and is applied to the element if it is true. The syntax is as shown below

<element [ngClass]="{'cssClass1': true, 'cssClass2': true}">...</element>
Enter fullscreen mode Exit fullscreen mode

Example of objects as CSS Classes

<div class="row">     
  <div [ngClass]="{'red':true,'size20':true}">Red Text with Size 20px</div>
</div>
Enter fullscreen mode Exit fullscreen mode

In the above example, an object is bound to the ngClass. The object has two properties red and size20. The property name is assigned to the div element as a class name.

Dynamically updating Class names
We can dynamically change the CSS Classes from the component.

Using strings
To do that first create a string variable cssStringVar in your component code and assign the class names to it as shown below.

cssStringVar: string= 'red size20';
Enter fullscreen mode Exit fullscreen mode

You can refer to the cssStringVar in your template as shown below

<div class="row">     
   <div [ngClass]="cssStringVar">Red Text with Size 20px : from component     </div> 
</div>
Enter fullscreen mode Exit fullscreen mode

Using arrays
Instead of string variable, you can create a array of string as shown below.

cssArray:string[]=['red','size20']; 
Enter fullscreen mode Exit fullscreen mode

And, then use it in ngClass directive

<div class="row">
  <div [ngClass]="cssArray">
    Red Text with Size 20px  : from CSS Array
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Using JavaScript object
Create a class as shown below in your component

class CssClass {
  red: boolean= true;
  size20: boolean= true; 
}
Enter fullscreen mode Exit fullscreen mode

Next, create the instance of the CssClass in the component as shown below. You can change the value of the property true as false dynamically

cssClass: CssClass = new CssClass();
Enter fullscreen mode Exit fullscreen mode

And then refer to the cssClass in your template.

<div class="row">     
  <div [ngClass]="cssClass"> Red Text with Size 20px : from component as object</div> 
</div>
Enter fullscreen mode Exit fullscreen mode

Angular ngStyle Directive

The Angular ngStyle directive allows us to set the many inline style of a HTML element using an expression. The expression can be evaluated at run time allowing us to dynamically change the style of our HTML element. In this tutorial, we learn how to use the ngStyle with an example.

ngStyle Syntax

<element [ngStyle]="{'styleNames': styleExp}">...</element>
Enter fullscreen mode Exit fullscreen mode

Where

element is the DOM element to which style is being applied

styleNames are style names ( ex: ‘font-size’, ‘color’ etc). with an optional suffix (ex: ‘top.px’, ‘font-style.em’),

styleExp is the expression, which is evaluated and assigned to the styleNames

We can add more than one key value pairs 'styleNames': styleExp each separated by comma.

In the following example, some-element gets the style of font-size of 20px.

<some-element [ngStyle]="{'font-size': '20px'}">Set Font size to 20px</some-element>
Enter fullscreen mode Exit fullscreen mode

The units (for example px, em) are prefixed to the styleName.

Syntax:

<element [ngStyle]="{'styleName.unit': widthExp}">...</element>
Enter fullscreen mode Exit fullscreen mode

Example:

<some-element[ngStyle]="{'font-size.em': '3'}">...</some-element>
Enter fullscreen mode Exit fullscreen mode

ngStyle Example
Change Style Dynamically
Initialize a variable color and add it to your component

color: string= 'red';
Enter fullscreen mode Exit fullscreen mode

And in your template, add the following


<input [(ngModel)]="color" /> 
<div [ngStyle]="{'color': color}">Change my color</div>
Enter fullscreen mode Exit fullscreen mode

In the above example, we apply ngStyle directive to the div element. We assign JavaScript object {'color': color} to the ngStyledirective. The variable color is dynamically changed by the user input and it is applied instantly to the div element

The following code uses the ternary operator to set the background color to red if the status variables indicator is set to “error” else blue.

div [ngStyle]="{'background-color':status === 'error' ? 'red' : 'blue' }"></<div>
Enter fullscreen mode Exit fullscreen mode

ngStyle multiple attributes
We can change multiple style as shown in the following example

<p [ngStyle]="{'color': 'purple',
               'font-size': '20px',
               'font-weight': 'bold'}">
     Multiple styles
</p>
Enter fullscreen mode Exit fullscreen mode

The JavaScript object is assigned to the ngStyledirective containing multiple properties. Each property name of the object acts as a class name. The value of the property is the value of the style.

Specifying CSS Units in ngStyle
CSS has several units for expressing a length, size etc. The units can be em, ex, %, px, cm, mm, in, pt, PC etc. We prefix the units to the StyleName as shown below.

<input [(ngModel)]="size" /> 
<div [ngStyle]="{'font-size.px': size}">Change my size</div>
Enter fullscreen mode Exit fullscreen mode

Using object from Controller
Create a class as shown below

class StyleClass {
   'color': string= 'blue';
   'font-size.px': number= 20;
   'font-weight': string= 'bold'; 
}
Enter fullscreen mode Exit fullscreen mode

And in controller initialize the class

styleClass: StyleClass = new StyleClass();
Enter fullscreen mode Exit fullscreen mode

Then you can refer it in your template as shown below

<div [ngStyle]="styleClass">size & Color</div>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)