Angular Components (With Examples)

Brief Info About Component       

  • A Component is nothing but a simple TypeScript class where you can create your own methods and properties as per your requirement which is used to bind with a UI (html or cshtml page) of our application.
  • In Angular 2, normal TypeScript class will become a Component class once it has been decorated with @component decorator.
  • @component decorator provides an additional metadata that determines how the component should be processed, instantiated, and used at runtime.
  • We can also say that Components are the most basic building blocks of a UI in an Angular application
  • Components are also referred to as one of the types of directives just like a structural and attribute directive, which we will see in-depth in the upcoming article.
  • Finally, component must belong to an NgModule in order for it to be usable by another component or application. To specify that a component is a member of an NgModule, you should list it in the declarationsfield of that NgModule

Brief of @Component Decorators

  • Decorators in Typescript are like annotations in Java or attributes in C#.

Component decorator consists of many metadata properties or attributes, but in this article we will see the most frequently used five properties with an example those are selector, template, templateUrl, style and styleUrl.

Kindly refer this link for the complete list: https://angular.io/api/core/ComponentDecorator

Selector

It is used to replace the html at runtime in the index.html. The replacement is happening using the directive name. For example in the below code we have used the <myapp> as a directive and replace content as we want.

Simple Example

Example code

File name: app.component.ts

  1. import { Component } from "@angular/core";  
  2.   
  3. //decorator  
  4. @Component({  
  5.      
  6.     selector: 'my-App',  
  7.     template: '<h1>{{name}}</h1>'  
  8. })  
  9.   
  10. export class AppComponent {  
  11.     name: string = "Angular 2"  
  12. }  

File name index.html

  1. <!DOCTYPE html>  
  2. <html>  
  3.   <head>  
  4.     <title>Angular QuickStart</title>  
  5.     <base href="/src/">  
  6.     <meta charset="UTF-8">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.     <link rel="stylesheet" href="styles.css">  
  9.   
  10.     <!-- Polyfill(s) for older browsers -->  
  11.     <script src="/node_modules/core-js/client/shim.min.js"></script>  
  12.   
  13.     <script src="/node_modules/zone.js/dist/zone.js"></script>  
  14.     <script src="/node_modules/systemjs/dist/system.src.js"></script>  
  15.   
  16.     <script src="systemjs.config.js"></script>  
  17.     <script>  
  18.       System.import('main.js').catch(function(err){ console.error(err); });  
  19.     </script>  
  20.   </head>  
  21.   
  22.   <body>  
  23.   
  24.     <!--Here is the selector mapped-->  
  25.     <my-app>Loading AppComponent content here ...</my-app>  
  26.   
  27.   
  28.   
  29.   </body>  
  30. </html>  

Output

Angular
Template

It is used to specify the html which is shown as an output to the user

Filename app.component.ts

Example

  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.      
  5.     selector: 'my-App',  
  6.   
  7.       
  8.     template: '<h1>Hi {{name}}</h1>'  
  9. })  
  10.   
  11. export class AppComponent {  
  12.     name: string = "Karthik"  
  13. }  

Important Note

In the above code, selector: 'my-App’ will refer to the before mentioned index.html which is the starting page of our application

Output

Angular
TemplateUrl 

URL to an external file containing a template for the view

Example

FileName app.component.ts 

  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.      
  5.     selector: 'my-App',  
  6.   
  7.     templateUrl: 'app/app.component.html'  
  8. })  
  9.   
  10. export class AppComponent {  
  11.     name: string = "Karthik"  
  12. }  

Note

Always remember that, the URL that is specified in the templateUrl property is always relative to the index.html of the angular project 

FileName app.component.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6. </head>  
  7. <body>  
  8.     <h1>This is {{name}} Home Page</h1>  
  9. </body>  
  10. </html> 

Output

Angular
Additional Notes about Template and TemplateUrl

In the component we can define either template or templateUrl and cannot define both template and templateUrl property. In other words, only one of templateUrl or template can be defined per Component. 

Negative Test case Example:  [using both template and templateUrl]

  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.      
  5.     selector: 'my-App',  
  6.     template: `<input type="textbox" id="txtbx" value="Karthik">`,  
  7.     templateUrl:"app/app.component.html"  
  8.       
  9. })  
  10.   
  11. export class AppComponent {  
  12.     name: string = "Angular 2"  
  13. }  

If we run the above code , then we won’t get an output and in the console tab we would  able to find the error message like the below snagit.

Output

Angular

And if we compare , it always better to use templateUrl if the html goes more than three lines, so you will get the features of intellisense and code alignment in our favourite visual studio. 

Styles - inline-defined styles to be applied to this component's view

Example

File name app.student.ts

  1. import { Component } from "@angular/core"  
  2.   
  3. //decorater declaration  
  4. @Component({  
  5.   
  6.     selector: 'my-student',  
  7.     templateUrl: 'app/student/app.student.html',  
  8.     styles: ['table { color: #369; font-family: Arial, Helvetica, sans-serif; font-size: large; border-collapse: collapse;}''td {border: 1px solid black; }']  
  9.       
  10. })  
  11.   
  12.  //class creation   
  13. export class StudentComponent {  
  14.     firstName: string = "Karthik";  
  15.     lastName: string = "Elumalai";  
  16.     gender: string = "Male";  
  17.     qualification: string = "MCA";  
  18. }  

File name

Output

Angular
styleUrl 

List of url style sheets to be applied to this component's view

Example 

  1. import { Component } from "@angular/core"  
  2.   
  3. //decorater declaration  
  4. @Component({  
  5.   
  6.     selector: 'my-student',  
  7.     templateUrl: 'app/student/app.student.html',  
  8.     //changed the property style to styleUrls  
  9.     styleUrls: ['app/student/app.student.css']  
  10.       
  11. })  
  12.   
  13.  //class creation   
  14. export class StudentComponent {  
  15.     firstName: string = "Karthik";  
  16.     lastName: string = "Elumalai";  
  17.     gender: string = "Male";  
  18.     qualification: string = "MCA";  
  19. }  

Output

Angular

Nested Component

If a component used by an another component then it is termed as nested component

A component must belong to an NgModule in order for it to be usable by another component or application.

To specify that a component is a member of an NgModule, you should list it in the declarations field of that NgModule.

Example

Component 1 app.component.ts

  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.   
  5.     selector: 'my-App',  
  6.     template: `  
  7.                 <div>  
  8.                 <h1>{{pageheader}}</h1>  
  9.                 </div>  
  10.                  //Here is the nesting happens by calling another component selector  
  11.   
  12.                  <my-student></my-student>  
  13.                 `,  
  14.   
  15. })  
  16.   
  17. export class AppComponent {  
  18.     pageheader: string = "Student Details"  
  19. }  

Component 2 app.student.ts

  1. import { Component } from "@angular/core"  
  2.   
  3. //decorater declaration  
  4. @Component({  
  5.   
  6.     selector: 'my-student',  
  7.     templateUrl : 'app/student/app.student.html'  
  8.       
  9. })  
  10.   
  11.  //class creation   
  12. export class StudentComponent {  
  13.     firstName: string = "Karthik";  
  14.     lastName: string = "Elumalai";  
  15.     gender: string = "Male";  
  16.     qualification: string = "MCA";  
  17. }  

AppModule the application root module

Every Angular app has a root module class. By convention, the root module class is called AppModule and it exists in a file named app.module.ts

AppModule is the root module which bootstraps and launches the angular application. You can name it anything you want, but by convention it is named AppModule

Example

Filename app.module.ts 

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { StudentComponent } from './student/app.student'  
  6.   
  7. @NgModule({  
  8.     imports: [BrowserModule],  
  9.     declarations: [AppComponent, StudentComponent],  
  10.     bootstrap: [AppComponent]  
  11. })  
  12. export class AppModule { }  

Important Note

Once we entered our second component in the app.module.ts file, we can inject that component in any other component by using their selector. 

Exact line in Component 1(app.component.ts) where nesting happens,

template

  1. <div>  
  2. <h1>{{pageheader}}</h1>  
  3. </div>  
  4.  <my-student></my-student>  

Final Output

Angular
Additional Note

if you don’t register your component in the app.module.ts file and try to use it in the other components, then you won’t get the output and console will show the following error.

Same app.module.ts code without registering the second component,

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. //import { StudentComponent } from './student/app.student'  
  6.   
  7. @NgModule({  
  8.     imports: [BrowserModule],  
  9.     declarations: [AppComponent],  
  10.     bootstrap: [AppComponent]  
  11. })  
  12. export class AppModule { }  

Angular

And the good thing is, the errors are very  self-explanatory to understand the problem.

Conclusion

Component plays a vital role in angular 2 and it’s very important to understand it better before digging into another topic.

Hope the above information was useful, kindly share your thoughts or feedback.

In case you would like to explore angular 2 more, below are the links.

Up Next
    Ebook Download
    View all
    Learn
    View all