Components in Angular

Tram Ho

1. Introduction to Components in Angular

I will start by introducing Components in Angular. Did you know, Component is the “kernel” of every Angular application. It is the pieces that make up the interface and functionality of the application. You can think of a Component like a LEGO block, each with a different shape and color, when put together in some way, they create a complete image. In Angular, Component works similarly.

1.1 Definition and role of Components in Angular

So what is Component? In Angular, the Component is an independent unit with the tasks of handling logic (Class), template (HTML), and styles (CSS). Each Component can work independently and can be reused in the application.

Role of Components? Components are the heart of every Angular application. They help create the interaction between the user and the application, handle the logic, and render the user interface. Components can communicate with each other, receive and transmit data to each other.

1.2 Basic structure of a Component

So what does a Component include? A Component in Angular usually consists of 3 main parts:

  • Class: defines the logic of the Component, contains properties and methods.
  • Template: is the HTML code that describes the interface of the Component.
  • Style: is the CSS used to decorate the Template.

Let’s see a basic example of a Component’s structure:

In the above example, AppComponent is a Component with:

  • The AppComponent class contains the title property and changeTitle() method.
  • The template contains an h1 tag to display the title and a button to change the title.
  • CSS is defined in the file app.component.css .

As you can see, creating and using Components in Angular is not difficult, right?

So I gave a brief introduction to Components in Angular. In the next part, I will show you how to create and manage Components.

2. Create and manage Components

After understanding the structure and roles of Components, it’s time to learn how to create and manage them.

2.1 How to create a new Component

To create a new Component in Angular, we often use the Angular CLI, a tool to help develop Angular applications quickly and efficiently. The example below demonstrates how to create a new Component named my-component :

After running the above command, Angular CLI will create a new folder named my-component containing 4 files:

  • my-component.component.ts : Class definition and Component logic.
  • my-component.component.html : defines the Component’s Template.
  • my-component.component.css : defines the Style for the Template.
  • my-component.component.spec.ts : file used for testing.

In addition, Angular CLI also automatically adds a new Component to declarations of NgModule that the Component belongs to.

2.2 How to manage Components

As your application grows and has more components, managing them will become more complicated. Angular provides several ways to help you manage components more easily:

  • Component reuse : One of the strengths of Components is reusability. You can create a Component and use it in many places in the application.
  • Nesting Component (Nested Component) : You can create a large Component from many smaller Components. This makes it easier to manage the application and makes the source code easier to read.
  • Communication between Components : Angular provides several ways for Components to communicate with each other, like Input and Output , or using Service .

At this point, I hope you have understood how to create and manage Components in Angular. In the next section, we will learn about an equally important concept in Angular, which is Lifecycle Hooks.

3. Lifecycle Hooks in Angular

Lifecycle Hooks are special functions that Angular will call during different phases of a Component’s lifecycle. By using these Lifecycle Hooks, we can control the lifecycle of the Component more precisely.

3.1 Types of Lifecycle Hooks

Angular provides different types of Lifecycle Hooks for each phase of the Component’s lifecycle:

  • ngOnChanges : Called when Angular sets or updates a data-bound property.
  • ngOnInit : Called after Angular has finished initializing the Component or Directive, right after ngOnChanges is called for the first time.
  • ngDoCheck : Called when Angular checks for changes to Component or Directive.
  • ngAfterContentInit : Called when Angular finishes rendering the content of the Component or Directive.
  • ngAfterContentChecked : Called after Angular checks Component or Directive content.
  • ngAfterViewInit : Called after Angular has finished rendering the UI (view) of the Component or Directive.
  • ngAfterViewChecked : Called after Angular checks the UI of the Component or Directive.
  • ngOnDestroy : Called just before Angular destroys the Component or Directive.

3.2 Using Lifecycle Hooks

To use a Lifecycle Hook, we just need to add the corresponding method to the Component’s Class. The following example demonstrates how to use ngOnInit and ngOnDestroy :

In the above example, every time Angular creates a new instance of MyComponent , it prints “Constructor is called”, then “ngOnInit is called”. When Angular destroys that instance, it prints “ngOnDestroy is called”.

We can see that Lifecycle Hooks are very useful when we want to perform some action at a certain point in the Component’s life cycle.

3.3 Things to watch out for with Lifecycle Hooks

When working with Lifecycle Hooks, you need to pay attention to the following points:

  • Lifecycle Hooks are not required : Not all Components need to use all Lifecycle Hooks. In fact, there are many Components that only need to use certain Hooks.
  • Order of Calling Lifecycle Hooks : Angular will call Lifecycle Hooks in a certain order, from ngOnChanges , ngOnInit to ngOnDestroy . You need to understand this order well to be able to use Hooks effectively.
  • Beware of ngOnChanges : This hook will be called every time a data binding property changes. Therefore, if you put some heavy logic in ngOnChanges , it can degrade the performance of the application.
  • Use ngOnDestroy to clean up : When Angular destroys a Component, it calls ngOnDestroy . This is where you should perform cleanup, like canceling subscriptions or stopping processes that are no longer needed.

Above are the basic points that I want to introduce about Lifecycle Hooks in Angular. It is very basic and brief, in the next articles I will guide you more about each Lifecycle Hooks one by one.

In the next part, I will give some tips & tricks when working with Components in Angular, so that you can make the most of them.

4. Some tips when working with Components in Angular

Once you have mastered the basics of Components in Angular and how to use Lifecycle Hooks, I would like to share some tips & tricks to optimize performance and simplify your code. In the scope of this article, I will give the term and briefly explain it, in the next articles there is a chance that I will explain each one in detail.

4.1 Leveraging @Input and @Output

@Input and @Output are powerful decorators that make passing data between components flexible and easy.

@Input allows you to pass data from the parent Component to the child Component, while @Output allows the child Component to send events to the parent Component.

Using them correctly will make your code cleaner and easier to maintain.

4.2 Using Change Detection Strategy

Angular provides two types of Change Detection Strategy: Default and OnPush .

In the Strategy Default , Angular checks all the changes in the application, which leads to if your application is large, this process can take quite a while.

When you have a large application with many components, Angular checking changes for each component can be resource intensive and slow down the application. To solve this problem, Angular provides ChangeDetectionStrategy.OnPush .

When using OnPush , Angular will only check for changes to the Component when there is an @Input change, or when an event is fired from that Component. This reduces the number of change checks and improves application performance.

4.3 Leveraging Content Projection

Content Projection, formerly known as Transclusion in AngularJS, allows you to insert custom content into your Component.

This is useful when you want to create a reusable Component with different content. You just need to use <ng-content></ng-content> tag in Component’s template.

5. Summary

In this article, I introduced you to Components in Angular – one of the core concepts that make up the power of Angular.

  • What are Components : Components are the most basic building blocks of an Angular application. A Component contains its own logic, can interact with the user and update the view.
  • How to Create and Manage Components : Angular CLI makes it easy to create and manage Components. Components can be arranged in a tree, with each parent component containing many child components.
  • Components Lifecycle Hooks : A Component in Angular has a specific lifecycle, starting when it is instantiated and ending when it is destroyed. Angular provides Lifecycle Hooks that help us to intervene in different stages of a Component’s lifecycle.
  • Tips when working with Components : Finally, I have shared some tips to help you optimize performance and simplify code when working with Components.

I hope this article will help you better understand Components in Angular and how to use them effectively. Don’t hesitate to experiment and explore the amazing possibilities that Angular has to offer!

6. Some common questions about Components in Angular

Before ending, I would like to answer the 5 most popular and best questions about Components in Angular created by myself  for the purpose of reviewing the knowledge in this article.

6.1 Does every Component need Lifecycle Hooks?

No, not all components need to use Lifecycle Hooks. In fact, if you don’t need to set up any logic at specific stages of the Component lifecycle, you can’t use them at all.

6.2 Is it possible to create a Component without going through the Angular CLI?

Yes, you can completely create a Component without going through the Angular CLI. However, using the Angular CLI makes it quick and easy to create components, and ensures compliance with Angular’s structure and standards.

6.3 When to use ChangeDetectionStrategy.OnPush ?

ChangeDetectionStrategy.OnPush should be used when you want to optimize the performance of your application. When using OnPush , Angular only checks for changes to the Component when there is an @Input change or when an event is fired from that Component.

6.4 How to insert custom content into Component?

To insert custom content into a Component, you can use Content Projection. Simply place the content you want to insert between the Component’s opening and closing tags. In the Component’s template, you’ll use the <ng-content></ng-content> tag to specify where to display this content.

6.5 When to use @Input and @Output ?

@Input and @Output should be used when you want to pass data between components. @Input allows you to pass data from the parent Component to the child Component, while @Output allows the child Component to send events to the parent Component.

Share the news now

Source : Viblo