Styles and StyleUrls

We know that the decorator functions of @Component take object and this object contains many properties. So we will learn about the properties of Styles and StyleUrls in this article.

We can represent our styles, ie the CSS code within the @Component decorator in two ways.

Inline Styles

The Inline Style are specified directly in the component decorator. In this, you will find the CSS within the TypeScript file. This can be implemented using the "styles" property.

Use the following code in “app.component.ts” .

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
    styles: ['h1{color:#FF4500}', 'div{font-family: Arial; color:	#00bfff}']
})
export class AppComponent {
  title = 'app';
}

Use the following code in “app.component.html” file.

app.component.html

<H1>styles</H1>
<hr>
<div>
    Styles inside typescript file. An implementation of
    <i>styles</i>
    property,this property takes an array of strings that contain CSS code.
</div>

This will be the output of the above code.

Sahosoft-Tutorials-inline-Styles

External Styles

The External styles define CSS in a separate file and refer to this file in styleUrl.means In this, we will find a separate CSS file instead of finding a CSS within the TypeScript file. Here, the TypeScript file contains the path to that style sheet file with the help of the "stylesUrls" property.

Use the following code in “app.component.ts” file.

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']  
})
export class AppComponent {
  title = 'app';
}

Use the following code in “app.component.html” file.

app.component.html

<H1>styleUrls</H1>
<hr>
<div>
    Styles outside typescript file, called external styles. An implementation of
    <i>styleUrls</i>
    property,this property takes path of style sheet where css code is present
</div>

Use the following code in “app.component.css” file.

app.component.css

h1{color:#FF4500}  
div{font-family: Arial; color:#00bfff}  

This will be the output of the above code.

Sahosoft-Tutorials-external-styles.png

Needs to remember below points about styles properties

• It is not mandatory to use any of the properties. If we do not want to implement any style on a web page, we can leave both properties.

• If we use both properties, "styles" and "styleUrls", then we always represent the style from an external file, ie, use the "styleUrls" property.