Angular Components: How to Create and Use it Practically?

Read it in 24 Mins

Last updated on
25th Nov, 2022
Published
20th Apr, 2021
Views
10,003
Angular Components: How to Create and Use it Practically?

Components are the building blocks of every Angular application. Therefore, to effectively create scalable Angular web apps, a solid understanding of Angular components is very crucial. In this article, we will cover everything you need to know to have a solid understanding of Angular components. Explore advanced Angular topics in an easy-to-understand manner.

Representation of Components  

If you’re a programmer by profession and have some fundamental knowledge of user experience, the above diagram will help you to understand about the internal structures of components.

Let’s take an example to understand components in a better way, and consider that we are building a page for an application. The features in the page include the header, footer and navigation and content area. Instead of building a single page with all these features, we can choose to split the page into components, which help us to manage our application. 

In the above scenario, we can say that the header, footer, content area, navigation and so on are separate components of the page; but when the user views it on the website through any device, it will show as a single page. 

Next, we will find out how to build components, and what is the internal structure of components. 

What is Component in Angular? 

Angular Components (also known as Angular Web Components or Angular UI Components), are reusable pieces of code that define views. View is a set of elements comprising distinct portions of the screen. In Angular applications, we use individual components to define distinct sections and control various aspects of the application. 

Angular can select and modify these components according to the program’s logic and data. For instance, components can be small UI elements like buttons or cards, and larger UI elements such as sidebars, navigation bars, pages, etc.

Each Angular component consists of: a TypeScript class, an HTML template, and a CSS style sheet. The TypeScript class defines the interaction between the HTML template and the rendered DOM structure, while the style sheet describes how it appears on the screen There are many pre-built Angular components libraries that can readily be used in your projects in less time and maintains a standard style pattern. 

A component definition has three major parts: component class, template, and meta data.

1. Component Class 

Each component defines a component class which is essentially a TypeScript class. A component class contains the data and logic related to the component, where data is used in properties and logic are used in methods. These enclosed data and logic are linked to an HTML template that defines a view that is rendered at the target section of the application’s view.

The class immediately below the @Component decorator is the component class. 

export class HelloComponent {
title: “Hello Component” 
message: string = “Hello World”
constructor() { }
printMessage() = { 
console.log(this.message) 
} 
} 

In the above AppComponent class, message is the property (data) and printMessage is the method (logic). The constructor function is a TS class constructor.

Component properties and methods can bind with the view (HTML template) using Data Binding. 

2. Template 

The template defines the view of the component. It is a combination of regular HTML and Angular template syntax, that alters the regular HTML based on the state and logic of the application and DOM data. 

Views are organized hierarchically, Angular allows to modify, or display and hide entire UI sections or pages as a unit. The Component can have only one template, and the host view of a component is defined by the template that is immediately associated with it. Additionally, the component can define a view hierarchy that has embedded views hosted by other components. 

 Template use data binding to connect the application with the corresponding DOM data, pipes for data transformation before the actual rendering of the component to the view, and directives for the application logic that controls the view of the component. 

<h2>{ { title } }</h2>
<button type="button" (click)="printMessage()"> 
Print message 
</button> 

3. Metadata 

Metadata Provides additional information about the component to the Angular. Angular uses this information to process the class. The class immediately below the @Component decorator is the component class. The component decorator specifies the metadata for the component class of the Angular component. 

A component’s metadata stores the information to obtain the major building blocks required to create and present the component and its view. Angular reads the metadata and connects the corresponding HTML template with the component and configures how the component can be referenced in HTML and what services it requires.

Important Component metadata configuration options:

CONFIGURATION OPTIONS 

DETAILS 

selector 

The selector property is a CSS selector that tells Angular to create and insert an instance of this component wherever a corresponding component tag is found in any template HTML. 

For example, when Angular spots <app-hello></app-hello> in any HTML file, it inserts an instance of the HelloComponent view in between those tags. 

template/ templateUrl 

The HTML template that defines our host view. We can pass inline template (using a template property) or an external template (using a templateUrl property). A Component can have only one template, either use inline template or external template, but not both. 

providers 

An array of Angular component providers to import injectable dependencies for the services that are used in the component. Service is a broad category encompassing any value, function, or feature required in the component, albeit doesn’t affect the view directly.

styles/ styleUrls 

Adds CSS styles to the component as inline styles (using style property). The styles used here are specific to the component’s host view. 

@Component({ 
selector: 'app-hello', 
template: ' 
<h2>{ { title } }</h2>
<button type="button" (click)="printMessage()"> 
Print message 
</button> 
', 
styles: [‘./hello-app.component.css’] 
}) 
export class HelloComponent implements OnInit { 
/* . . . */ 
} 

Life Cycle of Angular Components  

Every Angular component instance has a lifecycle associated to it. The component lifecycle begins when the component is initialized and ends at the destruction of the component. Every component goes through 8 different phases (or stage) in its lifecycle. The first stage of the component’s lifecycle starts when Angular instantiates the component class and renders the component view along with its child views. Followed by change detection algorithm, as Angular checks to see when data-bound properties change, and updates both the view and the component instance as needed. The lifecycle ends when Angular destroys the component instance and removes its rendered template from the DOM. 

Angular provides lifecycle hook methods that can tap into key events in the component’s lifecycle to access greater controls on component’s behavior. These lifecycle hooks are very useful in cases such as initialization of new instances, initiating change detection when needed, responding to updates during change detection, and cleaning up before deletion of instances 

Every component has a constructor method, which is essentially a constructor method of a TypeScript class. The main role of the constructor is to initialize the dependencies required by the component. The constructor method of a component gets called first before any other life cycle hook event is executed. After executing the constructor, Angular executes its life cycle hook methods in a specific order. 

Component life cycle Hooks

HOOK METHOD 

Use and Timing 

ngOnChanges() 

This hook executes every time one or more data-bound input properties within the component change. The hook receives a SimpleChange object; the SimpleChange object contains current and previous value of the bound property. 

If the component has bound inputs, ngOnChanges() gets called before ngOnInit()

This event is mostly used to initialize data in a component. 

ngOnInit() 

This lifecycle hook is triggered when the Angular first displays the component’s data-bound properties or when the component has been initialized. In other words, this event is called only once just after the first ngOnChanges() events.

In case there are no template-bound inputs, ngOnChanges() will not execute but ngOnInit() will execute when component is initialized.

ngDoCheck() 

This hook is called when the change detection mechanism detects some change in the input properties of a component. Moreover, this lifecycle hook is executed immediately after ngOnInit() on the first run, and after ngOnChanges() on every change detection run 

This hook is useful to implement your own custom change detection logic for the target component. 

ngAfterContentInit() 

This hook is called only for the first time just after the ngDoCheck() hook when all the bindings of the component need to be checked.

This lifecycle hook method executes when Angular performs any content projection within the component view. 

This method is fundamentally linked to the child components initialization. 

ngAfterContentChecked() 

This lifecycle hook is called whenever the component is checked by the Angular’s in built change detection mechanism. 

The ngAfterContentChecked hook gets called after ngAfterContentInit() method, and after every subsequent execution of ngDoCheck().

This method is fundamentally linked to the child components initialization. 

ngAfterViewInit() 

This hook executes when the component’s view and child views are fully initialized.

This hook gets called only once after the first ngAfterContentChecked().

ngAfterViewChecked() 

This method is just called after the ngAterViewInit() and every subsequent call of ngAfterContentChecked() hook.

It is executed every time Angular checks the view of the host component’s view and child view, or the view that contains the directive.

This lifecycle hook is extremely useful when the component is waiting for some value from its child components. 

ngOnDestroy() 

At last, the ngOnDestroy() lifecycle hook gets triggered before the target component is finally destroyed and removed from the DOM.

It is used to unsubscribe the observables and detach event handlers and prevent memory leaks. 

Component Interaction  

In an Angular application, components interact with each other to share data to and from different components. There are four different ways of sharing/ sending/ interacting data among different components. 

  • Parent to Child: Sharing Data via Angular Components Input 
  • Child to Parent: Sharing Data via ViewChild 
  • Child to Parent: Sharing Data via Output and EventEmitter 
  • Child to Parent: Sharing Data using local variable 
  • Unrelated Components: Sharing Data with a Service 

1. Parent to Child: Sharing Data via Angular Components Input 

One of the most common and straightforward method of data sharing is by using @Input decorator. Here we use @Input() decorator to allow data to be passed through the template. Let’s take an example to understand its implementation. 

Parent.component.ts 
import { Component } from ‘@Angular/core’; 
@Component({ 
selector: ‘app-parent’, 
template: ` 
<app-child [childMessage]=”parentMessage”></app-child> 
`, 
}) 
export class ParentComponent{ 
parentMessage = “Message from parent” 
constructor() { } 
} 
Child.component.ts 
import { Component, Input } from ‘@Angular/core’; 
@Component({ 
selector: ‘app-child’, 
template: ` 
<p>Say {{ message }}</p> 
`, 
}) 
export class ChildComponent { 
@Input() childMessage: string; 
constructor() { } 
} 

2. Child to Parent: Sharing Data via ViewChild 

@ViewChild decorator allows injection of child component into the parent component. Parent component gives access to the child component’s properties and methods. The child, however, is unavailable until the view is initialized. Thereby, we must implement the ngAfterViewInit() lifecycle hook to receive the data from the child. 

Parent.component.ts 
import { Component, ViewChild, AfterViewInit } from '@Angular/core'; 
import { ChildComponent } from "../child/child.component"; 
@Component({ 
selector: 'app-parent', 
template: ` 
Message: {{ message }} 
<app-child></app-child> 
`, 
}) 
export class ParentComponent implements AfterViewInit { 
@ViewChild(ChildComponent) child; 
constructor() { } 
message:string; 
ngAfterViewInit() { 
this.message = this.child.message 
} 
} 
Child.component.ts 
import { Component} from ‘@Angular/core’; 
@Component({ 
selector: ‘app-child’, 
template: ` 
`, 
}) 
export class ChildComponent { 
message = ‘Hello Parent, I am child!’; 
constructor() { } 
} 

3. Child to Parent: Sharing Data via Angular Component Output and EventEmitter 

We can emit data from the child, and the parent can listen to it. This method is ideal for sharing data changes that occur on Angular UI elements such as buttons, form entries, and other user events. EventEmitter class with @Output directives are used to emit custom Angular component events both synchronously or asynchronously.

In the parent component, create a function to receive the message and set it equal to the message variable.

In the child, we use the @Output decorator to declare a messageEvent variable and assign a new event emitter as its value. Then we create a function called sendMessage that calls emit with the message we want to send on this event. Finally, we create a button to activate this function. 

When the child component outputs this messageEvent, the parent can subscribe to it and run the receive message function whenever it occurs. 

Parent.component.ts 
import { Component } from '@Angular/core'; 
@Component({ 
selector: 'app-parent', 
template: ` 
Message: {{message}} 
<app-child (messageEvent)="receiveMessage($event)"></app-child> 
`, 
}) 
export class ParentComponent { 
constructor() { } 
message:string; 
receiveMessage($event) { 
this.message = $event 
} 
} 
Child.component.ts 
import { Component, Output, EventEmitter } from '@Angular/core'; 
@Component({ 
selector: 'app-child', 
template: ` 
<button (click)="sendMessage()">Send Message</button> 
`, 
}) 

4. Child to Parent: Sharing Data using Local Variable 

In this method we create a template reference variable for the child element and then reference that variable within the parent template. 

Parent.component.ts 
import { Component } from '@Angular/core'; 
@Component({ 
selector: 'app-parent', 
template: ` 
Message: {{message}} 
<app-child #child (messageEvent)="receiveMessage(#child.message)"></app-child> 
`, 
}) 
export class ParentComponent { 
constructor() { } 
message:string; 
receiveMessage(message: string) { 
this.message = message 
} 
} 
Child.component.ts 
import { Component } from '@Angular/core'; 
@Component({ 
selector: 'app-child', 
template: ` 
<button (click)="sendMessage()">Send Message</button> 
`, 
}) 
export class ChildComponent { 
message: string, 
constructor() { } 
sendMessage() { 
This.message = "Hello Parent, I am child!" 
} 
} 

5. Unrelated Components: Sharing Data with a Service 

To pass data between components that do not have a direct connection, such as siblings, grandchildren, and so on, a shared service should be used. When you have data that should always be in sync, the RxJS BehaviorSubject comes very useful. 

A BehaviorSubject has following advantages:

  • There is no need to call onnext because it will always return the current value on subscription. 
  • It has a getValue() function that returns the most recent value as raw data. 
  • It ensures that the component always receives the most up-to-date information. 

In the service, we create a private BehaviorSubject to store message's current value. The components will use the currentMessage variable, which is defined to handle this data stream as an observable. Finally, we write a function that changes the value of the BehaviorSubject by calling next on it. 

The parent, child, and sibling components are all treated the same way. In the constructor, we inject the DataService, then subscribe to the currentMessage observable and set its value equal to the message variable. 

Now, if we create a function in any of these components, we can change the message's value. The new data is automatically broadcast to all other components when this function is executed. 

data.service.ts 
import { Injectable } from '@Angular/core'; 
import { BehaviorSubject } from 'rxjs'; 
@Injectable() 
export class DataService { 
private messageSource = new BehaviorSubject('default message'); 
currentMessage = this.messageSource.asObservable(); 
constructor() { } 
changeMessage(message: string) { 
this.messageSource.next(message) 
} 
} 
Parent.component.ts 
import { Component, OnInit } from '@Angular/core'; 
import { DataService } from "../data.service"; 
@Component({ 
selector: 'app-parent', 
template: ` 
{{message}} 
`, 
}) 
export class ParentComponent implements OnInit { 
message:string; 
constructor(private data: DataService) { } 
ngOnInit() { 
this.data.currentMessage.subscribe(message => this.message = message) 
} 
} 
sibling.component.ts 
import { Component, OnInit } from ‘@Angular/core’; 
import { DataService } from “../data.service”; 
@Component({ 
selector: ‘app-sibling’, 
template: ` 
{{message}} 
<button (click)=”newMessage()”>New Message</button> 
`, 
}) 
export class SiblingComponent implements OnInit { 
message:string; 
constructor(private data: DataService) { } 
ngOnInit() { 
this.data.currentMessage.subscribe(message => this.message = message) 
} 
newMessage() { 
this.data.changeMessage(“Hello, Sibling wants to dance”) 
} 
} 

Component Styles  

Angular applications use standard CSS for styling. Therefore, you can directly apply your knowledge of CSS stylesheets, selectors, rules, and media queries to Angular applications. 

Furthermore, Angular can bundle component styles with components, allowing for a more modular design than traditional stylesheets. 

There are several ways to add CSS to your Angular components. 

Using Component Styles 

We can define CSS styles directly in the component’s metadata using styles property. 

App.component.ts 
import { Component } from "@Angular/core"; 
@Component({ 
selector: "app-root", 
templateUrl: "./app.component.html", 
styles: [ 
` 
h1 { 
font-size: 50px; 
} 
` 
] 
}) 
export class AppComponent {} 
  • Any components nested within the template or any content projected into the component do not inherit host component styles in styles. 
  • In each component, we can use CSS class names and selectors that make the most sense. 
  • Class names and selectors in one component do not conflict with class names and selectors in another component. 
  • Changes made elsewhere in the app have no effect on the current component. 
  • We can co-locate each component's CSS code with its TypeScript and HTML code, making the project structure cleaner. 
  • Also, we can change or remove CSS code without having to search the entire app to see where else it is used. 

1. Special Selectors 

Component styles have a few special selectors, these special selectors come from world of shadow DOM style scoping. 

:host 
The :host pseudo-class selector targets styles in the element that hosts the component rather than the elements inside the component’s template. 
:host { 
display: block; 
border: 3px solid black; 
} 

Use the function form :host(), to apply host styles conditionally by including another selector inside parentheses after :host.

The :host selector can also be combined with other selectors; for instance, add selectors behind the :host to select child elements, e.g., using :host h2 to target all <h2> elements inside the host component's view.

// host's content becomes bold red when the active CSS class is applied to the host element. 

:host(.active) { 
background-color: red; 
font-weight: bold; 
} 
// <h2> element inside the :host component is blue in color
:host { 
color: blue;
} 
:host-context 

We can use :host-context to conditionally apply styles, outside of a component’s view. It searches for the CSS class in any ancestor of the component host element, all the way up to the document root. 

It works the same way as the :host selector, which can use the function form. Hence it is only useful when combined with another selector. 

:host-context(.active) { 
font-style: italic; 
color: blue; 
} 

2. Style Files in Component Metadata 

Use styleUrls metadata property to point to a stylesheet file to style a component. You can specify more than one styles file or even a combination of styles and styleUrls. 

import { Component } from "@Angular/core"; 
@Component({ 
selector: "app-root", 
templateUrl: "./app.component.html", 
styleUrls: ["./app.component.css"] 
}) 
export class AppComponent {} 

Note: Styles defined in the style file apply only to this component. They are not inherited by any components nested within the template nor by any content projected into the component. 

3. Template Inline Styles 

@Component({ 
selector: 'app-component', 
template: ` 
<style> 
button { 
background-color: white; 
border: 1px solid #777; 
} 
</style> 
<h2>Controls</h2> 
<button type="button" (click)="activate()">Activate</button> 
` 
}) 

4. Template link tags 

You can also write <link> tags into the component's HTML template. 

@Component({ 
selector: "app-root", 
template: ` 
<link rel="stylesheet" href="./app.component.css" />
<h1>Foo</h1> 
` 
}) 
export class AppComponent {} 

5. CSS @imports 

We can import CSS files in the CSS files, with the standard CSS @import rule. 

@import './hero-details-box.css'; 
6. External and Global Style Files 

We can add external global styles to Angular.json to include them in the build. To register a CSS file, we can put it in the styles section, which is set to styles.css by default. 

7. Non-CSS Style Files 

Angular CLI supports building style files in SASS, LESS or Stylus. We can specify those files in styleUrls with the appropriate extensions 

How to Create Component in Angular?  

Wow, we have explored a lot of concepts, and it’s time to put these knowledge nuggets into practice. But before going further, pat yourself for your determination because you are a Rockstar developer. To help Rockstar developers like you, here is an online web design and development course taught by the experts.

Components are the building blocks of every Angular application, hence to develop your apps in Angular, creating components is the most important aspect.

Prerequisites  

To create a component, there are very little prerequisite.

1. Install the Angular CLI.

$ npm install -g @Angular/cli 

2. Create an Angular workspace with initial application. If you don't have a project, create one using ng new <project-name>, where <project-name> is the name of your Angular application. 

Now, it’s time to create an Angular web app, follow along the instructions step-by-step, to understand the process of creating a component in Angular. 

Step 1: Create a new Angular application or open an existing one. To create the application run ng new followed by the application name. 

$ ng new Angular-Application 

ng new prompts you feature information to include in your initial project. Accept the defaults by pressing the Enter or Return key. 

Step 2: Navigate to the root folder of your application. For example: 

$ cd C:\Users\Ankit\Desktop\Angular-Application 

Creating a Component  

A) Create Component using Angular CLI 

Step3: To create the Angular CLI new component, run ng generate component command followed by the name or path inside the src/app directory, to store the generated component. 

$ ng generate component card 

B) Create Angular Components Manually 

In Angular, you can also create your components manually, although the preferred method is using CLI as it is fast and provides you with a ready-to-work component while performing all the configurations backstage. Albeit knowing the manual approach of creating new components in Angular gives you a deeper understanding and appreciation for the Angular framework. 

Step 1: In src/app directory of your app, create a folder for your new component 

Step 2: Inside your component folder, create a typescript file, for instance: navbar.component.ts. Inside your file, define your component by adding @Component decorator, template, selectors, component class, etc. 

navbar.component.ts. 
import { Component } from "@Angular/core"; 
@Component({ 
selector: "app-navbar", 
template: ` 
<div class="navbar-header"> 
<a class="nav-title"><b> Angular Application Navbar </b></a> 
</div>` 
styles: [“.navbar-header { 
background-color: #07393C; 
padding: 30px 50px; 
display: flex; 
align-items: center; 
font-family: sans-serif; 
}”,
“.nav-title { 
text-decoration: none; 
color: white; 
font-size: 16pt; 
}”] 
}) 
export class NavbarComponent { 
} 

Step 3: Go to app.module.ts file and import your custom-created component into @NgModule declarations section. 

app.module.ts 
import { BrowserModule } from '@Angular/platform-browser'; 
import { NgModule } from '@Angular/core'; 
import { AppRoutingModule } from './app-routing.module'; 
import { AppComponent } from './app.component'; 
// Here we have imported our custom created component 
import { NavbarComponent } from './navbar/navbar’; 
@NgModule({ 
declarations: [ 
AppComponent, 
NavbarComponent 
], 
imports: [ 
BrowserModule, 
AppRoutingModule 
], 
providers: [], 
bootstrap: [AppComponent] 
}) 
export class AppModule { } 

Step 4: At last, go to app.component.html file and add the same selector that you have added in the custom component typescript file (custom.ts). 

app.component.html 
<app-navbar></app-navbar> 
<h1>Welcome to Angular Component Example</h1> 

Finally, you have a working Angular component. Additionally, you can also create the support files for the component like CSS styles, HTML, and spec files for unit testing the component. 

How to Add Content to Angular Component?  

Step 1: Add HTML template to your card component. 

card.component.ts 
import { Component } from "@Angular/core"; 
@Component({ 
selector: "app-card", 
template: ` 
<div class="card"> 
<img src="./assets/images/blue-mountains.jpg" alt="Avatar"> 
<div class="container"> 
< class="title"> Blue Mountains </> 
<p> NSW, Australia </p> 
</div> 
</div> 
`, 
stylesUrl: [“./card.component.css”] 
}) 
export class CardComponent {} 
Step 2: Add style to the card component 
card.component.css 
.card { 
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); 
width: 400px; 
padding: 8px; 
margin: 24px; 
background-color: whitesmoke; 
font-family: sans-serif; 
} 
.card img { 
max-width: 400px; 
} 
.title { 
padding-top: 16px; 
} 
.container { 
padding: 2px 16px; 
} 
Step 3: Add card component to the Application view by adding it to the app-root hierarchy. 
app.component.html 
<app-navbar></app-navbar> 
<h1>Welcome to Angular Component Example</h1> 
<div style="display: flex"> 
<app-card> </app-card> 
<app-card> </app-card> 
<app-card> </app-card> 
</div> 

How to Pass Input Parameters into the Component?  

Step 1: Import Input in the card.component.ts

Step 2: Create two input variables locationName and imageName to track component state. Define ngOnInit() logic to toggle between image path and default value. 

card.component.ts 
import { Component, Input, ngOnInit } from "@Angular/core"; 
{ … } 
export class CardComponent { 
@Input() locationName: string; 
@Input() imageName: string; 
constructor() {} 
ngOnInit(): void { 
if (this.imageName) { 
this.imageName = "./assets/images/" + this.imageName; 
} else { 
this.imageName = "./assets/images/blue-mountains.jpg"; 
} 
} 
} 

Step 3: Update card component HTML template, from hard coded values to dynamic input values. 

<div class="card"> 
<img src="{{imageName}}" alt="Avatar"> 
<div class="container"> 
<h4 class="title">{{locationName ? locationName : 'Blue Mountains'}}</h4> 
<p>NSW, Australia</p> 
</div>
</div> 

Step 4: In app.component.html, modify <app-card> tag to access its locationName and imageName properties. 

App.component.html 

<app-navbar></app-navbar>
<h1>Welcome to Angular Component Example</h1> 
<div style="display: flex"> 
<app-card [locationName]="'Blue Mountains'" [imageName]="'blue-mountains.jpg'"> </app-card> 
<app-card [locationName]="'Sydney'" [imageName]="'sydney.jpg'"> </app-card> 
<app-card [locationName]="'Newcastle'" [imageName]="'newcastle.jpg'"> </app-card> 
</div> 

Step 5: Run your Angular application from the terminal using the ng serve command. 

How to Route to a New Component 

If your component represents a large part of your website such as a new page, then you can use Angular routing to navigate from one page to another. Angular router is a core part of the Angular platform that enables developers to build Single Page Applications with multiple views and allow navigation between these views. 

Step 1: Import your target component at the top of app-routing.module.ts, for example 

import { CardComponent } from './card/card.component'; 

Step 2: Add a routing path to the routes array in app-routing.module.ts 

const routes: Routes = [ 
// ... Any other routes you may need ... 
{ path: 'card', component: CardComponent }, 
] 

Step 3: Replace all the current content in app.component.html to only include the navbar and a router-outlet HTML tag. The router-outlet allows you to route between pages.

app.component.html 
<app-navbar></app-navbar>
 <router-outlet></router-outlet> 

Add nav-a-link class anchor tag that matches its href attribute to the path in the routes array. Style the new nav-a-link class anchor tag.

navbar.component.ts. 
import { Component } from "@Angular/core"; 
@Component({ 
selector: "app-navbar", 
template: ` 
<div class="navbar-header"> 
<a class="nav-title"><b> Angular Application Navbar </b></a> 
<a class="nav-a-link" href="/card"><b> Card </b></a>
</div>` 
styles: [“.navbar-header { 
background-color: #07393C; 
padding: 30px 50px; 
display: flex; 
align-items: center; 
font-family: sans-serif; 
}”,
“.nav-title { 
text-decoration: none; 
color: white; 
font-size: 16pt; 
}”, 
 “.nav-a-link { 
text-decoration: none; 
color: #4b6569; 
font-size: 14pt; 
margin-left: 60px; 
font-weight: lighter; 
}”] 
}) 
export class NavbarComponent { 
} 

Step 4: Run ng serve command to open your application in your browser’s local host 

Aliases in Angular component Imports  

When working with Angular projects in real time, we might come across a scenario where we are required to remember a long relative path for a component in an Angular file. This often proves to be difficult, and it makes the application messy and complex to read, especially if you are new to the team. This is where Aliases come to the rescue.

You might come across something like: 

In the above example, we should use aliases for relative paths to improve the readability of the code.

To achieve this in your Angular application, all you need to do is to update the tsconfig.json file.

If you look at the above configuration, the default property of the baseUrl property was updated to ‘src’ directory. Then, we added a new property called paths, which is an object containing key-value pairs representing aliases defined for the paths in our application.

The above code can be rewritten as shown below:

Like Aliases help in code readability, Lazy load is also a very useful Angular feature.

Let’s Understand Lazy Load in Terms of Any Programming Language  

As the term itself suggests, a Lazy Load is loaded late and only when needed. To understand this in a better way, consider a VIEW MORE button on any web page of an application. When we click on this VIEW MORE button, it loads the rest of the content and displays it to the user.

In a similar way, in Angular applications, we have several such components which are not very important. Only when the user wants to view these components, they must be loaded. We use Lazy load in such scenarios, as using this feature will make the best use of time and space in applications.

There are two main steps to setting up a lazy-loaded feature module  

  • Create the feature module with the CLI, using the --route flag.
  • Configure the routes.

To understand in more detail, with some sample code, please go through this reference URL where it is explained very well by the Angular Team 

In the example below, the LOAD MORE Button is created using the lazy loading concept. Visitors can view more blogs only if they are interested by clicking on this button. 

Conclusion  

In this article, we started with the introduction to component and explored component class, template, metadata.

Every component goes through its lifecycle events and has relative lifecycle hook methods to finely control every stage of a component’s lifecycle such as initialize new instances, initiate change detection when needed, respond to updates during change detection, and clean up before deletion of instances. 

Components are building blocks of every Angular application. These building blocks communicate with one another and share/ send/ interact data, to build a functioning Angular application. 

There are many available approaches to style the Angular components. Angular applications use standard CSS for styling. Furthermore, Angular can bundle component styles with components, allowing for a more modular design than traditional stylesheets. Angular also provides special selectors, for example :host, :host(), :host-context(). 

Any portion of the application’s view can be broken down into components, including smaller buttons, cards, larger sidebars, and navigation bars. 

Angular provides decorators like @Input, @Output, etc. to create variables that are shared to pass data across different instances of the component. We can also route to the component using URL paths, which can be managed by Angular Router library. Check out KnowledgeHut’s advanced Angular topics. 

Frequently Asked Questions (FAQs)  

1. What are Angular components used for?  

Answer: Angular Components are building blocks of your application; these are reusable bits of code that add modularity to your code. Individual components define distinct sections and control various aspects of the application. For instance, a component can be a small UI elements like buttons or cards, and larger UI elements such as sidebars, navigation bars, pages, etc. 

2. What is an API in Angular?  

Answer: The API (Application Programming Interface) in AngularJS is a collection of global JavaScript functions used to perform common tasks such as comparing objects, iterating objects, and converting data. For example:

  • Angular.lowercase() : Converts a string to lowercase 
  • Angular.uppercase() : Converts a string to uppercase 
  • Angular.isString() : Returns true if the reference is a string 
  • Angular.isNumber() : Returns true if the reference is a number 

3. What is lazy loading in Angular?  

Answer: Lazy loading is an Angular technique that allows you to load JavaScript components asynchronously when a particular route is activated. It reduces application load time by splitting the application into several bundles. The bundles are loaded as required as the user navigates through the app. 

4. What is ngModel in Angular?  

Answer: We use ngModel directive in Angular component HTML template to bind the value of HTML controls such as input, select, and textarea to the application’s data variable. Here the binding is bidirectional (also called two-way data binding), which means the application listens to the event and updates the properties at every input event. 

5. What is decorator in Angular?  

Answer: Decorators are functions that are called with a prefixed @ symbol and followed by a class, method, or property. They enable the modification of a service, directive, or filter before it is used. A decorator primarily provides configuration metadata that specifies how a component, class, or function should be processed, instantiated, and used at runtime. For example, @Component, @Input, @Output, etc. 

Profile

Ankit Joshi

Author

Ankit Joshi is a front-end web developer with a knack for writing. He has two years of experience working as a freelance ghostwriter. When Ankit is not working you can find him exploring topics related to Technology, Psychology, or just about anything that ignites a mental spark.

Develop the skills of the future via outcome-based immersive learning

Speak to our Career Advisor now!

Select
Your Message (Optional)

Angular Training

24 Hours: Live Instructor-Led Sessions
Learn by Doing with Hands-On Exercises
Practice with Assignments and MCQs
Build real-world skills with Live Projects
Go from Fundamentals to Advanced

Take Me to the Course

What Is Dependency Injection in AngularJS

Easier Angular JS Routing With Angular UI Router

Exploring the Various Decorators in Angular

How to Install Angular 12 on MacOS