Angular Component: What is it and How to Implement it?

Angular Component: What is it and How to Implement it?
Tutorial Playlist

Components are used to divide a huge application into smaller, more manageable, and self-contained components. They communicate with one another via inputs, outputs, and services, resulting in a more modular and easy-to-maintain application. In this article, we will try to understand components in depth

Table of Contents

What is a Component in Angular?

A component in Angular is a key building block of an Angular application. It is a reusable unit of an Angular application formed by a template and a class that controls a section of the screen. The class includes attributes and methods that describe the component’s behavior, while the template determines the component’s structure and appearance on the screen.

Angular components are reusable and can be layered inside other components, allowing developers to create sophisticated user interfaces by mixing smaller, simpler components. Components can connect with one another via inputs, outputs, and services, making it easier to handle complicated interactions between different portions of the program.

Angular Component Example

Example of a simple Angular component:

import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<h1>{{ message }}</h1>`,
styles: [`h1 { color: green; }`]
})
export class GreetingComponent {
message: string = 'Hello, World!';
}

Explanation

  • @Component decorator: Defines metadata like selector, template, and styles.
  • selector: Defines how you use this component in HTML (<app-greeting>).
  • template: Contains the HTML that will be displayed by this component.
  • styles: Defines the component-specific CSS.
  • class: Contains the behavior and logic of the component (e.g., the message property here).

When this component is used in the application, the template will be rendered as HTML, and the behavior of the component will be defined by the class. The H1 header will display the message “Hello, World!”, and the text will be displayed in green.

Get 100% Hike!

Master Most in Demand Skills Now!

Parts of an Angular Component

An Angular component has several parts, such as:

  1. Component Decorator: The component decorator is a JavaScript function that is used to define the metadata of a component. It contains information about the component, such as its selector, template, styles, and properties.
  2. Selector: The selector is a string that defines the name of the component as it is used in templates.
  3. Template: The template is a string or a reference to an external file that defines the HTML structure of the component.
  4. Styles: The styles are a string or a reference to an external file that defines the CSS styles for the component.
  5. Class: The class is a JavaScript class that defines the properties and methods of the component.
  6. Input properties: Input properties are properties that are passed from a parent component to a child component. They are defined using the ‘@Input’ decorator and can be used to bind data from the parent component to the child component.
  7. Output properties: Output properties are properties that are emitted from a child component to a parent component. They are defined using the ‘@Output’ decorator and can be used to notify the parent component of changes in the child component.
  8. Lifecycle hooks: Lifecycle hooks are methods that are called at specific points during the creation, update, and destruction of a component. They provide a hook into the lifecycle of a component and allow you to perform custom logic at specific times.

Angular Component Lifecycle Events

Angular has 8 lifecycle hooks. Following are the events under angular component lifecycle:

1. ngOnChanges

This event is called whenever there is a change in input binding value. The method receives an object that maps the old and new values of each changed input property. This event is called before ngOnInit and can be used to respond to changes in input data.

2. ngOnInit

This event occurs after the constructor of the component followed by the initial call to ngOnChanges.This event is a good place to perform component initialization, such as fetching data or initializing local variables.

3. ngDoCheck

This event is triggered whenever Angular checks the component for changes. Change detection is the process by which Angular checks for changes in component data and updates the component’s view accordingly. The ngDoCheck method can be used to perform custom change detection logic, such as deep checking of complex objects.

4. ngAfterContentInit

This event takes place when Angular has processed the content of the component (ng-content).This event is a good place to perform initialization logic for content that is projected into the component.

5. ngAfterContentChecked

After each check of the component’s content this event is called. This event can be used to perform logic that depends on the component’s content, such as updating the count of the number of items in the content.

6. ngAfterViewInit

This function occurs when Angular has evaluated the views of the component (and child views). This event is a good place to perform logic that depends on the component’s view and child views, such as accessing elements in the view.

7. ngAfterViewChecked

This event is called after each check of the component’s views (and child views). This event can be used to perform logic that depends on the component’s views, such as responding to changes in view data.

8. ngOnDestroy

This occurrence takes place immediately before the component is destroyed. This event is a good place to perform cleanup logic, such as unsubscribing from observables, removing event listeners, and clearing timers.

Angular Styles in Component

In Angular, you can apply styles to components in several ways. Each component has its own styles, which can be defined in a number of ways, including:

  1. Inline styles: You can define styles directly in the component’s template using the style attribute. This is the simplest way to add styles to a component, but it can be less maintainable for larger angular projects.
  2. Component-level styles: You can define styles for a component in its own ‘.css’ file. These styles will only apply to the component and its child components.
  3. Global styles: You can define styles in a global ‘.css’ file that will be applied to the entire application.
  4. Sass/SCSS styles: Angular supports Sass/SCSS styles, which provide additional features such as variables, functions, and mixins.

You can control the scope of the styles applied to a component using the encapsulation property of the component. By default, Angular uses “emulated” encapsulation, which means that the component’s styles are scoped to the component and its child components, but are not isolated from the rest of the application.

To change the encapsulation, you can set the encapsulation property in the component’s metadata to either ‘ViewEncapsulation.None’ or ‘ViewEncapsulation.ShadowDom’. If you set it to ‘ViewEncapsulation.None’, of the component’s styles, will be global and affect the entire application. If you set it to ‘ViewEncapsulation.ShadowDom’, the component’s styles will be scoped to the component and its child components, and will not affect the rest of the application.

How to Implement an Angular Component?

Implementing an Angular component involves the following steps:

1. Define the component class

Create a new TypeScript class either through the Angular CLI or manually. Use the @Component decorator to specify the component’s metadata, such as selector, template, and styles.

import { Component } from '@angular/core';
@Component({
selector: 'app-greeting', // This tag will be used in HTML
template: `<h1>{{ message }}</h1>`, // Inline HTML template
styles: [`h1 { color: green; font-family: Arial; }`] // Inline CSS styles
})
export class GreetingComponent {
message: string = 'Hello, Angular!'; // Component property
}

2. Define the template

You can define the template either inline (as seen above) or in a separate file.

@Component({
selector: 'app-greeting',
templateUrl: './greeting.component.html', // External template file
styleUrls: ['./greeting.component.css'] // External CSS file
})

greeting.component.html

<h1>{{ message }}</h1>

greeting.component.css

h1 {
color: darkblue;
font-size: 24px;
}

You can use Angular directives like *ngIf, *ngFor, or data binding {{}} inside templates for dynamic behavior.

3. Define the class

The logic is stored in the class. You can also use @Input and @Output to pass data into and out of the component.

import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `
<h1>{{ message }}</h1>
<button (click)="sendGreet()">Send Greeting</button>
`
})
export class GreetingComponent {
@Input() message: string = 'Hello from Child!';
@Output() greetEvent = new EventEmitter<string>();
sendGreet() {
this.greetEvent.emit('Greeting from child component!');
}
}

4. Register the component

To use the component in your app, register it in a module. Typically, this is done in app.module.ts.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { GreetingComponent } from './greeting/greeting.component'; // Import your component
@NgModule({
declarations: [
AppComponent,
GreetingComponent // Register your component here
],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

5. Use the Component in HTML

After registration, use the selector in your HTML like this:

app.component.html

<app-greeting [message]="'Welcome to Angular!'" (greetEvent)="handleGreeting($event)"></app-greeting>

app.component.ts

export class AppComponent {
handleGreeting(msg: string) {
alert(msg);
}
}

Conclusion

Angular components are essential in the creation of Angular apps. They allow for the definition of modular and reusable sections of an application that can be readily utilized and combined to construct complicated user interfaces. Developers can construct well-structured and maintained apps by knowing the various aspects of an Angular component.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.