Home » Framework » Angular » Detailed view of Component in the Angular Application

Detailed view of Component in the Angular Application

This article explains the detailed information of creating the component, the different ways of using CSS styles to the component, and the view encapsulation modes of the component in the Angular Application.

Components are the most important thing in Angular Applications. We can say it is the main building blog of angular application. It consists of four files that are HTML template, CSS template, Typescript class, and Spec file.

Every component is like an MVC that has the HTML code for the view and CSS code for the design and Typescript code for the behavior.

  1. HTML Template - we can write the HTML code for the view of the Page.
  2. CSS Template - Here we can write the CSS styles to the HTML template.
  3. Typescript Class - Here we can mention the behavior like handling the data to be displayed on the page.
  4. SPEC file - It's just a specification file of the component.

Now let's create the component in the new Angular Application. Open the command prompt window in your system and follow the below steps.

  1. Type ng new angular-component - It creates the new Angular Application in the name of angular-component at the chosen location. While creating, It asks two questions regarding routing and the type of CSS we want to use. You can type 'n' for routing because we are not dealing with routing here and for the style type you can choose CSS.
  2. It will take some time to complete because it has to install all the npm packages.
  3. Once the project is created successfully then open the project in any one of the code editors to do the changes.

Here I am using Visual Studio Code for writing code for the angular applications. Now let's create the first component in the new angular application.

ng g component first-component

The above command creates the component under the app folder like it creates the folder in the name of first-component under the app folder and creates the four files within the folder first-component and the component registered in app.module.ts.

In the command prompt, you can see like below.

F:\angularproj\angular-component>ng g c first-component
CREATE src/app/first-component/first-component.component.html (30 bytes)
CREATE src/app/first-component/first-component.component.spec.ts (683 bytes)
CREATE src/app/first-component/first-component.component.ts (310 bytes)
CREATE src/app/first-component/first-component.component.css (0 bytes)
UPDATE src/app/app.module.ts (751 bytes)

Now we have created the first component in the new Angular Application and the project structure looks like below.

angular component project structure
angular component project structure

Type ng serve in the command prompt to run the application. Once the application runs successfully then open the browser and type this URL http://localhost:4200. You can see the angular home page but you can't see the view of the first-component that you have created. Let see that in the below-detailed section.

Detailed Information of Angular Component

Usually, when we create a component the HTML template and CSS template will be created as an external template and this external template will be declared in the Typescript class.

@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.css']
})

In the above code, the selector declares the directive name of the component and the templateUrl declares the external HTML template that renders the page view and the styleUrls declares the external style template that decorates the HTML with the styles.

Now we can use the directive name mentioned in the selector section to load the component view in the browser. Please do the below changes to see your first component view in the browser.

Replace the below code in the first-component.component.html file

<h2>Welcome to TipsToCode!.</h2>

Replace the below code in the app.component.html file.

<app-first-component></app-first-component>

The above directive code loads the view of the first component on the main page of the Angular Application. You can see this directive in the @Component decorator in the first-component.component.ts file.

The typescript file of every component has its own directive name declared in the selector section of the @Component decorator. We can use this directive name to load this component in the HTML of any other component. Normally the directive name is like 'app-componentName'.

Now run the angular application again by using ng serve. You can see the first component view in the browser that displays the message "Welcome to TipsToCode!."

HTML Template

There are two types of HTML template available for the component.

  1. External Template - It creates a separate HTML file under the component folder. We have already seen this in the first component creation from the beginning of this article.
  2. Inline Template - It creates an HTML template as inline in the component.ts file instead of creating the separate component.html file.

Let's create another component in the name of 'second-component' that has the inline template.

ng g component second-component --inline-template

The above command creates the component named second-component under the app folder. The component folder has three files Typescript, CSS, and Spec but it doesn't have the HTML file because that will be created as an inline template in the Typescript file itself.

You can see the below result in the command prompt, there is no external HTML file created.

F:\angular-projects\angular-component>ng g component second-component --inline-template
CREATE src/app/second-component/second-component.component.spec.ts (690 bytes)
CREATE src/app/second-component/second-component.component.ts (328 bytes)
CREATE src/app/second-component/second-component.component.css (0 bytes)
UPDATE src/app/app.module.ts (552 bytes)

Now open the second-component.component.ts file in the editor and see the created inline template. The code looks like below.

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

@Component({
  selector: 'app-second-component',
  template: `
    <p>
      second-component works!
    </p>
  `,
  styleUrls: ['./second-component.component.css']
})
export class SecondComponentComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
}

In the above code, the inline template is declared in the 'template' key of the @Component decorator.

Apply CSS styles to the HTML Template of Angular Component

We can apply CSS styles to the HTML Template in many ways that are

  1. Apply CSS styles from the CSS template of the component. (Write CSS styles in the component.css file created under the component folder).
  2. Import the CSS file from any location in the component.css file.
  3. Apply CSS styles by creating CSS inline template.
  4. Embed CSS styles directly into the inline HTML template.
  5. Use link tag in inline HTML template to refer CSS file from any location.

Apply CSS styles to the HTML Template from an external CSS template

Let's do the changes in the first-component that we created already. Open the first-component.component.css file in the editor and put the below style.

h2{ color:green;}

It applies the green color to the h2 tag that is in the first-component.component.html file.

Import CSS file from any location within the project

First, let us create the CSS file named 'firstcomponent.css' under the assets folder and put the CSS style like below.

h2{ color:Yellow;}

Now open the first-component.component.css file and remove the style we wrote and import the CSS file created under the assets folder like below.

@import '../../assets/firstcomponent.css';

It applies yellow color to the h2 tag that is in the first-component.component.html file.

Now let's create the new component with an inline HTML template and an inline CSS template to see the other types of applying CSS styles.

ng g component third-component --inline-template --inline-style

The above command creates the component named 'third-component' under the app folder. The component folder only has two files within it that are typescript and spec files. You can see the below result in the command prompt.

F:\angular-projects\angular-component>ng g component third-component --inline-template --inline-style
CREATE src/app/third-component/third-component.component.spec.ts (683 bytes)
CREATE src/app/third-component/third-component.component.ts (291 bytes)
UPDATE src/app/app.module.ts (664 bytes)

Apply CSS style to the HTML template from an inline CSS style

Now open the third-component.component.ts file in the editor and replace the below code.

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

@Component({
  selector: 'app-third-component',
  template: `
    <h2>
      Welcome to TipsToCode!.
    </h2>
  `,
  styles: ['h2{color:green;}'
  ]
})
export class ThirdComponentComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
}

The style written inside the styles[] array applies the green color to the h2 tag that is in the inline HTML template.

You can test this by putting the directive name of the third-component in the app.component.html file like below.

<app-third-component></app-third-component>

Now save the changes and run the angular application again to see the result.

Embed CSS styles directly into the inline HTML template

We can embed the CSS styles directly into the inline HTML template by using <style></style> tag.

For example, open the file third-component.component.ts in the editor and replace the below code.

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

@Component({
  selector: 'app-third-component',
  template: `
  <style>
  h2{color:green;}
  </style>
    <h2>
      Welcome to TipsToCode!.
    </h2>
  `
})
export class ThirdComponentComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
}

The above code also applies green color to the h2 tag from the CSS that written inside the <style></style> tag.

Use link tag in inline HTML template to refer CSS file from any location

We can apply the CSS style to the inline HTML template by linking the CSS files from any location within the angular project. For example, we already created the CSS file named firstcomponent.css under the assets folder right!. Let us link that file to the inline HTML template like below.

Please open the third-component.component.ts file in the editor and replace the below code.

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

@Component({
  selector: 'app-third-component',
  template: `
  <link rel="stylesheet" href="../../assets/firstcomponent.css">
    <h2>
      Welcome to TipsToCode!.
    </h2>
  `
})
export class ThirdComponentComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
}

It applies the yellow color to the h2 tag from the style written in the external CSS file linked in the inline HTML template.

View Encapsulation of Angular Component

In Angular Application, the component styles are encapsulated into the component view and it doesn't affect the other parts of the application.

For example, if we write any CSS rule within the component style then that rule only applies with that component view and it doesn't affect the other component or another part of the application.

The reason behind this is the encapsulation mode of angular components. There are three view encapsulation modes are available for the component in angular application. That is

  1. Emulated
  2. None
  3. ShadowDom

Emulated Mode

When we choose the view encapsulation mode is Emulated for a component then the styles of the component are added to the <head> of the document and make available throughout the application. But the syles are scoped so that applied within the component's template and do not affect the others.

The default mode of the angular component is Emulated only. So that the CSS styles are scoped and applied within the component's template. if you inspect the CSS style in the browser then you can see some extra attributes attached to it. These extra attributes are making the CSS class unique and that look something like "_ngcontent-ocm-c12".

None Mode

When we choose the view encapsulation mode as None for a component then the styles of the component are added to the <head> of the document and make available throughout the application. But the syles are not scoped so that it affects the others parts of the application too.

ShadowDom Mode

When we choose the view encapsulation mode is ShadowDom for a component then it added the styles to the shadow DOM host. So it applies the CSS styles only within the component's template.

Let's see the examples of all three modes. Take the two components first-component and second-component that we created already and do the changes like below.

Replace the below code in the first-component.component.ts file

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.css'],
  encapsulation : ViewEncapsulation.None
})
export class FirstComponentComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
}

In the above code, we chose the encapsulation mode is none.

Replace the below code in the first-component.component.html file

<h2>Welcome to TipsToCode!.</h2>

Replace the below code in first-component.component.css file

h2{ color:green;}

The above changes apply the style green color to the h2 tag of the component's template. This style added to the <head> of the document because of the None mode of encapsulation.

Now replace the below code in the second-component.component.ts file

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

@Component({
  selector: 'app-second-component',
  template: `
    <h2>
      Welcome to TipsToCode!.
    </h2>
  `,
  styleUrls: ['./second-component.component.css']
})
export class SecondComponentComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
}

Leave the CSS file for the component is empty. I mean don't write any CSS style inside the HTML template (or) second-component.component.css file

The h2 tag of the second component's template doesn't have any CSS style. Now we render the view of both the component by doing the changes in the app.component.html file like below.

Replace the below code in the app.component.html file

<app-first-component></app-first-component>
<app-second-component></app-second-component>

Now save all the changes and run the application again. You can see the h2 tag of both the components displayed as green color in the browser. We wrote the CSS style only for the h2 tag of the first-component HTML template and didn't write any CSS style for the second-component HTML template.

Due to the None mode of view encapsulation in first-component make the CSS style of the h2 tag available throughout the application. That's why the same style applied to the h2 tag of the second-component.

Now change the mode of view encapsulation with Emulated in the first-component.component.ts file like below.

encapsulation: ViewEncapsulation.Emulated

Save the changes and run the application again. Now you can't see the style applied with the h2 tag of the second-component HTML template. It only applied with the h2 tag of the first-component HTML template. Due to the Emulated mode of view encapsulation, it scoped the styles and only applied within the component's template.

Now change the mode of view encapsulation with ShadowDOM in the first-component.component.ts and see the result on your own.

I hope you understood creating the component, different ways of styling the component's template, and the view encapsulation modes of the component. In the next article, we will see the detailed view of the Angular Directive. Thanks!. Keep Reading!.

Download the full source code from GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *