Over a million developers have joined DZone.

Styling Components Angular 2

DZone 's Guide to

Styling Components Angular 2

Angular is a pretty comprehensive web development framework. You can even style your HTML using it. Read on to learn how.

· Web Dev Zone ·
Free Resource

In my last article, we saw how to create your own component in an Angular 2 application and how to use it.

If you need a refresher before diving into this article, feel free to go through my previous articles on Angular listed below:

In this article, we'll learn how to style HTML code for a component.

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

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

Now, let's open the rathrola.components.ts file we worked with in my last article. Let's create some sample HTML Tags with header 4, as shown below.

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

    selector: "my-tuts",  
    template: `<h2>Rathrola Prem Kumar, Consultant</h2>`,  
    styles: [`h4{  
color: red;  


Image title

We now have a header 4 from rathrola.component in red.

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

Let me demonstrate this with an example. Open app.component and create a metadata configuration, which is style say <h4>, as shown below, and style it to be blue in color.

import  {      
}  from  '@angular/core';  
import  {      
}  from  './rathrola.component'  
    selector:   'my-app',
    template:   `<h1>Hello World From Rathrola Prem Kumar</h1>  
<h4>Header 4 from App component</h4>  
    styles:  [`h4{  
    directives:  [RathrolaComponent]  
export  class  AppComponent  {}  

Now, open style.css and add an h4 class and style it so that it is orange in color, as shown below.


Image title

Now, open our Index.html file. Under the display application part, add an h4 tag. Now, save and refresh the browser.

Image title

Thanks for reading my blog. In my next post, we shall see how interpolation and data binding work in detail. Stay tuned!

angular 2 ,web dev ,html ,styling

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}