Styling Components Angular 2 - Part Six

In my last document, you saw how to create your own component in an Angular 2 Application and how to use it.

For reference, refer to the link given below.

Let us learn how to style HTML code for a component.

In an Index.html, we can find out class reference style.css, as shown below.

  1. <title>Angular 2 QuickStart</title>  
  2. <meta charset="UTF-8">  
  3. <meta name="viewport" content="width=device-width, initial-scale=1">  
  4. <link rel="stylesheet" href="style.css">  

Now, let’s open rathrola.component.ts. Let me create sample HTML tags with header 4, as shown below.

We have to use styles configuration with back ticks, followed by h4 class with the color Red. Let’s refresh the page and see the result, as shown below.

  1. @Component({  
  2.     selector: "my-tuts",  
  3.     template: `<h2>Rathrola Prem Kumar, Consultant</h2>`,  
  4.     styles: [`h4{  
  5. color:red;  
  6. }`]  
  7. })  


We have header 4 from rathrola.component in Red color.

We have to keep in mind that style is confined to a component, so if we have multiple components, then if we have styles for each component, then the style is restricted to particular component.

Let me show with an example, open app.component and create metadata configuration, which is style say <h4> as shown below with Blue color.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     RathrolaComponent  
  6. } from './rathrola.component'  
  7. @Component({  
  8.     selector: 'my-app',  
  9.     template: `<h1>Hello World From Rathrola Prem Kumar</h1>  
  10. <h4>Header 4 from App component</h4>  
  11. <my-tuts></my-tuts>`,  
  12.     styles: [`h4{  
  13. color:blue;  
  14. }`],  
  15.     directives: [RathrolaComponent]  
  16. })  
  17. export class AppComponent {}  

Now, open style.css and add h4 class with color Orange, as shown below.

  1. h4{  
  2. color:orange;  
  3. }   

Now, open an Index.html. Under the display Application part, add header 4 tag. Now, save and refresh the Browser.


Thanks for reading my blog. In my next document, we shall see how interpolation and Data binding in it works in detail. Stay tuned.