×

iFour Logo

Creating Reusable Angular Components

Kapil Panchal - June 25, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Creating Reusable Angular Components

What are Reusable Components?


Angular was designed to advance code reusability. Reusable components are those react components that can be used multiple times in your application. As a result, they need to be generic enough so that it’s free from complex business logic.

What are the ways to create reusable components?


One of the ways is to pass inputs and specified data to the component to render and configure the component.

Another way is, use content projection to pass a template to the reusable component.

What are the types of Reusable Components?


Presentation Components

Container Components

  • It is additionally referred to as smart components.
  • These components know the way to get data and work with services.
  • These components are tied to the business logic of your application and are not meant to be shared or reused.

Presentation Components

  • It is understood as dumb and lazy components.
  • These components need to be sustained with data.
  • They are clean, simple UI components that just need some input data to render.
  • Such components are reusable because they’re coded in a way that’s not absolute to any runtime event.

Coding reusable components is not only a best practice, but it’s actually practical and can cause you to more efficient. How?? See the below example for that.

Well, when creating a component, we often end up with a situation as this one:

 
import { Component } from '@angular/core';


@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.css']
})
class Page {
  title: string;
  actions: [];
  diplayFilters: boolean;
  displaySearch: boolean;
  displaySort: boolean;
  displayPagination: boolean;
  dataset: [];
  canEditRow: boolean;
  canDeleteRow: boolean;
}
export class pagecomponent{
}

This component used in the app.component.html in this way.


In that kind of problem, we end up with a component that is very hard to extend in parameters. So let’s discuss how to improve this kind of problem.

Content Projection (transclusion)


Angular comes with multiple ways to inject content within the DOM. The first is content projection, and here is the example of it:

 
	import { Component } from '@angular/core';

	@Component({
		 selector: 'app-page-list',
         templateUrl: ''
  
	})
	class PageList{
	}

This will be projected in the componet

It is very simple, the ng-content component tag is inside the parent component and replace with the ng-content tag. The issue that comes with if you pass a component within the ng-content that sub-component(child-component) are in-built within the parent component. It’ll not be destroyed when a child component is destroyed.

See here we import component in another component,

            
            Hey!

app-other-component is constructed not within the app-my-content but within the component is calling it.

So, content projection is good for simple HTML code, but that stops being true after you start injecting the component.

Template to the rescue

  • It is incredible to fix that problem.
  • Here, we simply require to use a template.
 
import { Input } from '@angular/core';
import { Component, TemplateRef } from '@angular/core';

@Component({
  selector: 'app-page-list',
  templateUrl: '
',
  
})
class PageList{
  @Input() temRef:TemplateRef;
}


Parent component



            hey!

In the above example, we created a template using ng-template and injected it as a parameter within the child component.

And next is that the child component is using it in a container, with the help of the ngTemplateOutlet directive.

Let’s understand the concept of ViewChild VS ContentChild
import { ContentChild, Input } from '@angular/core';
import { Component, TemplateRef } from '@angular/core';

@Component({
  selector: 'app-page-list',
  templateUrl: '',
  
})
class PageList{
  @ContentChild('pageList',{static:true})
temRef:TemplateRef;
}




            hey!


Here, we define the ContentChild decorator. The ViewChild decorator will find a child within the component. And that defined by its template while ContentChild finds a child in the content defined by the component.

Now we will see the whole example of the Reusable components.

This example contains the following:

  • Carded page
  • Displaying the list of page of employees
  • Title
  • Actions
  • Their content
  • And name
  • Pagination
  • Filtering and sorting.

ng-template defines that you simply can render the content manually for full control over how the control displays.

mat-paginator is for navigating the paged information. And for that, we install the material in our angular project.

onEvent is that the event for paginating the list on the table.

The Button is for the add new employee with a material icon.

Looking to hire Angular Developer ?
Your Search ends here.

Now, this is the employepage.ts file.

 
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { emp } from "../emp";
@Component({
  selector: 'app-employepage',
  templateUrl: './employepage.component.html',
  styleUrls: ['./employepage.component.css']
})
export class EmployepageComponent implements OnInit {
dataSource:emp[];

protected list:FormGroup;
  constructor() { }
  ngOnInit(): void {
  }
}

Datasource adds the data of employees.

And within the list, we will access the data in the formgroup.

Formgroup is that the module of the angular/forms.

Emp is a class that name as emp.ts. Here it is:

 
export class emp{
    title:string;
    search:string;
    actions:string;
    content:string;
}

Now, the child component name as an employepage component of a parent component.

            

Ng-container defines the section of a page, without having created an additional element just for that.

ngTemplateOutlet defines the reference of the template and context object of the template.

Here is that the employe.component.ts file.

 
import { Component, ContentChild, OnInit, TemplateRef } from '@angular/core';

@Component({
  selector: 'app-employe',
  templateUrl: './employe.component.html',
  styleUrls: ['./employe.component.css'],
  
})
export class EmployeComponent implements OnInit {
@ContentChild('title',{static:true}) titTemplate:TemplateRef;
@ContentChild('actions',{static:true}) actTemplate:TemplateRef;
@ContentChild('search',{static:true}) serTemplate:TemplateRef;
@ContentChild('content',{static:true}) conTemplate:TemplateRef;
  constructor() { }
  ngOnInit(): void {
  }
}

In this way, we created the angular components with the use of child and parent components.

Conclusion


Simple components are become harder to use and maintain if the complexity grows. That’s why produce the reusable components. By creating the reusable components, we are able to pass the important data in another component. And also accessing that data within the component. Reusable components are easy to use and maintain.

Creating Reusable Angular Components Table of Content 1. What are Reusable Components? 2. What are the ways to create reusable components? 3. What are the types of Reusable Components? 3.1. Container Components 3.2. Presentation Components 4. Content Projection (transclusion) 4.1. Template to the rescue 5. Conclusion What are Reusable Components? Angular was designed to advance code reusability. Reusable components are those react components that can be used multiple times in your application. As a result, they need to be generic enough so that it’s free from complex business logic. What are the ways to create reusable components? One of the ways is to pass inputs and specified data to the component to render and configure the component. Another way is, use content projection to pass a template to the reusable component. What are the types of Reusable Components? Presentation Components Container Components It is additionally referred to as smart components. These components know the way to get data and work with services. These components are tied to the business logic of your application and are not meant to be shared or reused. Presentation Components It is understood as dumb and lazy components. These components need to be sustained with data. They are clean, simple UI components that just need some input data to render. Such components are reusable because they’re coded in a way that’s not absolute to any runtime event. Coding reusable components is not only a best practice, but it’s actually practical and can cause you to more efficient. How?? See the below example for that. Well, when creating a component, we often end up with a situation as this one:   import { Component } from '@angular/core'; @Component({ selector: 'app-page', templateUrl: './page.component.html', styleUrls: ['./page.component.css'] }) class Page { title: string; actions: []; diplayFilters: boolean; displaySearch: boolean; displaySort: boolean; displayPagination: boolean; dataset: []; canEditRow: boolean; canDeleteRow: boolean; } export class pagecomponent{ } This component used in the app.component.html in this way. In that kind of problem, we end up with a component that is very hard to extend in parameters. So let’s discuss how to improve this kind of problem. Read More: A Complete Guide On Angular Rxjs Library Content Projection (transclusion) Angular comes with multiple ways to inject content within the DOM. The first is content projection, and here is the example of it:   import { Component } from '@angular/core'; @Component({ selector: 'app-page-list', templateUrl: '' }) class PageList{ } This will be projected in the componet It is very simple, the ng-content component tag is inside the parent component and replace with the ng-content tag. The issue that comes with if you pass a component within the ng-content that sub-component(child-component) are in-built within the parent component. It’ll not be destroyed when a child component is destroyed. See here we import component in another component, Hey! app-other-component is constructed not within the app-my-content but within the component is calling it. So, content projection is good for simple HTML code, but that stops being true after you start injecting the component. Template to the rescue It is incredible to fix that problem. Here, we simply require to use a template.   import { Input } from '@angular/core'; import { Component, TemplateRef } from '@angular/core'; @Component({ selector: 'app-page-list', templateUrl: ' ', }) class PageList{ @Input() temRef:TemplateRef; } Parent component hey! In the above example, we created a template using ng-template and injected it as a parameter within the child component. And next is that the child component is using it in a container, with the help of the ngTemplateOutlet directive. Let’s understand the concept of ViewChild VS ContentChild import { ContentChild, Input } from '@angular/core'; import { Component, TemplateRef } from '@angular/core'; @Component({ selector: 'app-page-list', templateUrl: '', }) class PageList{ @ContentChild('pageList',{static:true}) temRef:TemplateRef; } hey! Here, we define the ContentChild decorator. The ViewChild decorator will find a child within the component. And that defined by its template while ContentChild finds a child in the content defined by the component. Now we will see the whole example of the Reusable components. This example contains the following: Carded page Displaying the list of page of employees Title Actions Their content And name Pagination Filtering and sorting. ng-template defines that you simply can render the content manually for full control over how the control displays. mat-paginator is for navigating the paged information. And for that, we install the material in our angular project. onEvent is that the event for paginating the list on the table. The Button is for the add new employee with a material icon. Looking to hire Angular Developer ? Your Search ends here. See here Now, this is the employepage.ts file.   import { Component, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { emp } from "../emp"; @Component({ selector: 'app-employepage', templateUrl: './employepage.component.html', styleUrls: ['./employepage.component.css'] }) export class EmployepageComponent implements OnInit { dataSource:emp[]; protected list:FormGroup; constructor() { } ngOnInit(): void { } } Datasource adds the data of employees. And within the list, we will access the data in the formgroup. Formgroup is that the module of the angular/forms. Emp is a class that name as emp.ts. Here it is:   export class emp{ title:string; search:string; actions:string; content:string; } Now, the child component name as an employepage component of a parent component. Ng-container defines the section of a page, without having created an additional element just for that. ngTemplateOutlet defines the reference of the template and context object of the template. Here is that the employe.component.ts file.   import { Component, ContentChild, OnInit, TemplateRef } from '@angular/core'; @Component({ selector: 'app-employe', templateUrl: './employe.component.html', styleUrls: ['./employe.component.css'], }) export class EmployeComponent implements OnInit { @ContentChild('title',{static:true}) titTemplate:TemplateRef; @ContentChild('actions',{static:true}) actTemplate:TemplateRef; @ContentChild('search',{static:true}) serTemplate:TemplateRef; @ContentChild('content',{static:true}) conTemplate:TemplateRef; constructor() { } ngOnInit(): void { } } In this way, we created the angular components with the use of child and parent components. Conclusion Simple components are become harder to use and maintain if the complexity grows. That’s why produce the reusable components. By creating the reusable components, we are able to pass the important data in another component. And also accessing that data within the component. Reusable components are easy to use and maintain.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.