Learnitweb

Inline style in Angular component

In this article, we’ll see how to declare inline styles for a component.

We can declare styles for a component in two ways:

  • By referencing an external file. For example, in the following code, external file (app.component.css) is referenced using styleUrls property.
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
  • By declaring inline styles, by using styles property.
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: ['h1 { background-color: blue; }']
})

Inline styles are declared within the component. No external file is used to declare the styles.

Multiple inline styles in Angular component

The styles property of @Component decorator is a string array. Every string Strings in the array is a styles rule. We can add multiple styles like the following:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: [
    'h1 { background-color: blue; font-size: 22px;}',
    'h2 { background-color: red; font-size: 18px;}',
  ],
})

In this code we have declared styles for h1 and h2. The styles are represented as two strings in styles property array.

When to two use inline styles in Angular component?

If the template is simple and there is not much style to declare, we can choose the option to declare inline styles. However, most of the programmers keep the styles in separate files just to keep the code separate. However, if there is no style to declare, there is no point in keeping an extra empty file.

Declaring styles for a component’s template is optional. Whenever, we generate the component using Angular CLI, the styles file is auto-generated for us. This file is empty. If there is no style to add to the file, we can remove this file and use inline style.