DEV Community

Cover image for Creating Reusable Angular Components
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

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{
}

Enter fullscreen mode Exit fullscreen mode

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

<app-page actions="" caneditrow="" dataset="" displayfilters="" displaysearch="" title=""></app-page>

Enter fullscreen mode Exit fullscreen mode

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: '<ng-content></ng-content>'

  })
  class PageList{
  }

Enter fullscreen mode Exit fullscreen mode

``

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.

Top comments (0)