×

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 Angular Reusable Components?


Angular was designed to advance code reusability. Angular 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.

How to Create Reusable Components in Angular?


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 angular 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 Angular 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: Reusable Component in Angular


Simple components are become harder to use and maintain if the complexity grows. That’s why produce the angular reusable components. By creating the angular 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 Angular Reusable Components? 2. How to Create Reusable Components in Angular? 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 Angular Reusable Components? Angular was designed to advance code reusability. Angular 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. How to Create Reusable Components in Angular? 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 angular 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 Angular 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: Reusable Component in Angular Simple components are become harder to use and maintain if the complexity grows. That’s why produce the angular reusable components. By creating the angular 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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Technical Content Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

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

Quarkus vs Spring Boot - What’s Ideal for Modern App Development?
Quarkus vs Spring Boot - What’s Ideal for Modern App Development?

Spring Boot has long been a popular choice for developing custom Java applications. This is owing to its comprehensive features, impeccable security, and established ecosystem. Since...

Power BI Forecasting Challenges and Solutions
Power BI Forecasting Challenges and Solutions

Microsoft Power BI stands out for detailed data forecasting. By inspecting data patterns and using statistical models, Power BI provides a visual forecast of things to anticipate in...

Kotlin vs Java - Top 9 Differences CTOs Should Know
Kotlin vs Java - Top 9 Differences CTOs Should Know

Choosing the right programming language becomes crucial as it greatly influences the success of a software development project. When it comes to selecting the best programming language...