Angular Component

Go back to Tutorial

Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated per an element in a template. A component must belong to an NgModule in order for it to be available to another component or application. To make it a member of an NgModule, list it in the declarations field of the @NgModule metadata.

A component is basically a class that is defined to visualize any element on the screen. The components have some properties and by using them, we can manipulate how the element should look and behave on the screen. We can create, deploy, and update our own component as per our requirement. But when writing code using TypeScript, a component is basically a TypeScript class decorated with @Component() decorator.

import {Component} from “@angular/core”;

@Component({ 0020

selector: ‘first-prog’,

template: ‘Welcome to Angular’

})

export class FirstProgComponent{

}

Decorators are the JavaScript functions which amend the decorated class in some way. Basically, in these functions, an additional meaning to a plain JavaScript class based on the decorator is used. From the developers’ point of view, we just declaratively decorate a class by passing a mandatory configuration object as a parameter to the decorator function.

Components are a really neat idea. Each component class being an independent unit is highly reusable and can be maintained without messing up with other components. Scaling is as easy as adding more components to your existing application.

Component Configuration

@Component decorator basically decorates a TypeScript class as a component object. Basically, it is a function which takes different types of parameters. In the @component decorator, we can set the values of different properties to finalize the behavior of the components. The most used properties are as below.

  • Selector: A component can be used by the selector expression.
  • Template: Basically, a template is the part of the component which rendered in the browser. We can directly define the HTML tags or code within the template properties. Sometimes we called this as an inline template. For writing multiple lines of HTML code, all code needs to be covered within tilt (`) symbol.
  • TemplateUrl: Another way of rendering HTML tags in the browser. Here, we need to provide the HTML file name with its related file path. Sometimes, it is known as the external template. It is a better approach if the HTML part of the component is complex.
  • ModuleId: It is used to resolve the related path of template URL or style URL for the component objects.
  • Styles or stylesUrls: Component can be used in its own style by providing custom CSS or can refer to an external style sheet file which can be used by multiple components at a time. For proving inline style, we need to use styles and for providing external file path or URL, we need to use styleUrls.
  • Providers – In the real-life application, we need to use or inject different types of custom service within the component for implement the business logic for the component. For using any custom service within the component, we need to provide the service instance within the provider. Basically, the provider is an array type property where multiple service instance names can be provided by comma separation.

Component Lifecycle

The lifecycle of the component is maintained by the Angular 7 itself. Below is the list of lifecycle methods of Angular components.

constructor – method is executed before the execution of any lifecycle method. It is basically used for injecting dependency.

  • ngOnChanges – method called when an input control or binding value changes
  • ngOnInit – method called after the execution of first ngOnChnages
  • ngDoCheck – method called after every execution of ngOnChnages
  • ngAfterContentInit – method execute after component content initialized
  • ngAfterContentChecked – method execute after every check of component check
  • ngAfterViewInit – method execute after component views initialize
  • ngAfterViewChecked – method execute after every check of component views
  • ngOnDestroy – method executes before the component destroys.

Angular Component Architecture Layout

If we remember the Angular architecture, every UI in angular framework must be composed as a tree of Angular Component – one component will be placed beside another component, both of which may be wrapped up by one outer component and so on. This hierarchy starts with one Root Component which is normally called as Bootstrapped Component. Here are the steps of the Create Root Component,

  • Create Angular Module
  • Create Angular Component
  • Add Component to Module
  • Bootstrap Module
  • Bootstrap Component

Create Angular Module

As we already discussed earlier that everything in Angular 7 belongs to an Angular Module, for developing the root component, we first need to declare our first Angular module. An Angular module can be defined by creating a TypeScript class decorated with the “NgModule” decorator. Actually, NgModule is a decorator defined within the “@angular/core” library. @NgModule takes a metadata object that tells Angular how to compile and run module code. It identifies the module’s own components, directives, and pipes, making some of them public so external components can use them. In order to use it, we first need to import it as follows,

import { NgModule } from ‘@angular/core’;

@NgModule()

export class SampleModule { }

Create Angular Component

Finally, we reach a position where we need to create our first component using Angular 7. It can be done by creating a class decorated with @Component decorator which defined within the “@angular/core” library. Below the sample code for the angular component,

import { Component } from “@angular/core”;

@Component({

selector: “home”,

template: “<strong>Welcome To Angular 7</strong> “

})

export class HomeComponent {

constructor() {

}

}

In the above code, we pass two parameters to the component decorator,

  • selector – a simple text representing the tag name of the component.
  • template – UI part of the component

Add Component to Module

Now, the next step is to add the component within the angular module. It can be done using “declarations” option within “NgModule” decorator. For adding the component, we need to import the component within the module by using import keyword.

import { NgModule } from ‘@angular/core’;

import { HomeComponent } from ‘./SampleCode/app.component.home’;

@NgModule({

declarations: [HomeComponent]

})

export class SampleModule { }

Bootstrap the Module

As we already discussed, a single angular application can contain more than one Angular modules. But out of the all modules, only one module can be bootstrapped at the beginning. In Angular 7, this bootstrapping process needs to be done manually with the help of “platformBrowserDynamic” function which is defined within the “@angular/platform-browser-dynamic” library. Before bootstrapping Angular module, it is important to define the export keyword in the module class definition statement so that we can import that class into another file. Normally, as per standard guidelines of Angular, we define this bootstrap process within the main.ts file.

import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;

import { SampleModule } from ‘./app.article.module’;

platformBrowserDynamic().bootstrapModule(SampleModule);

Bootstrap the Component

In the previous section, we discussed if there are many modules that we need to bootstrap, one module as a starting module needs to be defined within the main.ts file. But at the same time, one module always contains multiple components. Then, what happens in this scenario – which component will be starting component or how Angular will identify its root component? For this reason, we also need to bootstrap the root component so that Angular can identify it. It can be done by using the bootstrap option in “NgModule” decorator.

import { NgModule } from ‘@angular/core’;

import { HomeComponent } from ‘./SampleCode/app.component.home’;

@NgModule({

declarations: [HomeComponent],

bootstrap: [HomeComponent],

})

export class SampleModule { }

Now, we will create a basic component which will display some data into the web pages. For that, we first create a typescript file named app.component.helloworld.ts and add the below code,

import { Component } from ‘@angular/core’;

@Component({

selector: ‘Hello-world’,

template: ‘<strong><b>Angular !</b>Hello World</strong>’

})

export class HelloWorldComponent {

constructor() {

}

ngOnInit() {

alert(“Page Init Method Fired!!”)

}

}

Now, add another TypeScript file named app.component.home.ts and the below code (basically this is the root component for us. We actually bootstrapped this component from the app.module.ts file

import { Component } from ‘@angular/core’;

@Component({

moduleId: module.id,

selector: ‘home-page’,

templateUrl: ‘app.component.home.html’

})

export class HomeComponent {

constructor() {

}

}

As per the above code, we use templateUrl properties of the component decorator for the root component. For this, we need to add an HTML file called app.component.home.html (We placed TypeScript and HTML file in the same folder location. But we can also place these two types of files in different locations. In that scenerio, we need to providethe HTML file name with related file path and the below code.

<strong>Angular Code Samples</strong>

<br />

<Hello-world></Hello-world>

<br />

Now, add another TypeScript file for Angular module and write down the code given below.

import { NgModule, NO_ERRORS_SCHEMA } from ‘@angular/core’;

import { APP_BASE_HREF } from ‘@angular/common’;

import { BrowserModule } from ‘@angular/platform-browser’;

import { FormsModule } from “@angular/forms”;

import { HttpModule } from ‘@angular/http’;

import { RouterModule } from ‘@angular/router’;

import { HomeComponent } from ‘./SampleCode/app.component.home’;

import { HelloWorldComponent } from ‘./SampleCode/app.component.helloworld’;

@NgModule({

imports: [BrowserModule, FormsModule, HttpModule],

declarations: [HomeComponent, HelloWorldComponent],

bootstrap: [HomeComponent],

schemas: [NO_ERRORS_SCHEMA]

})

export class ArticleModule { }

Now, add another file called main.ts and add the below code.

import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;

import { ArticleModule } from ‘./app.article.module’;

platformBrowserDynamic().bootstrapModule(ArticleModule);

Now, add the below code in index.html file.

<!DOCTYPE html>

<html lang=”en”>

<head>

<!–<base href=”/”>–>

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>

<meta charset=”utf-8″>

<title>Angular – Console</title>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

<meta name=”description” content=””>

<meta name=”keywords” content=””>

<meta name=”author” content=””>

<link href=”resource/css/bootstrap.min.css” rel=”stylesheet”>

<link rel=”stylesheet” href=”resource/css/font-awesome.min.css”>

<link rel=”stylesheet” href=”resource/css/jquery-ui.css”>

<link href=”resource/css/style.css” rel=”stylesheet”>

<link rel=”shortcut icon” href=”img/favicon/favicon.ico”>

</head>

<body>

<div class=”content”>

<home-page></home-page>

</div>

<footer>

<div class=”container”>

<div class=”row”>

<div class=”col-md-12″>

<p class=”copy”>Copyright © 2017-2018 | <a href=”http://www.c-sharpcorner.com/members/debasis-saha”>Debasis Saha</a> </p>

</div>

</div>

</div>

</footer>

<script src=”resource/js/jquery.js”></script>

<script src=”resource/js/bootstrap.min.js”></script>

<script src=”resource/js/jquery-ui.min.js”></script>

<script src=”resource/js/jquery.slimscroll.min.js”></script>

<script src=”resource/js/custom.js”></script>

<script src=”node_modules/core-js/client/shim.min.js”></script>

<script src=”node_modules/zone.js/dist/zone.js”></script>

<script src=”node_modules/systemjs/dist/system.src.js”></script>

<script src=”systemjs.config.js”></script>

<script>

System.import(‘main.js’).catch(function (err) { console.error(err); });

</script>

<!– Set the base href, demo only! In your app: <base href=”/”> –>

<script>document.write(‘<base href=”‘ + document.location + ‘” />’);</script>

</body>

</html>

Now, run the code.

Go back to Tutorial

Get industry recognized certification – Contact us

Menu