×

Dynamic components in Angular 8

Dynamic components in Angular 8

The dynamic component is one of the versatile and core concept introduced in Angular, Component template is not fixed. An application needs to load new elements at runtime in various scenarios.

The dynamic component is the component which is created dynamically at the runtime. Angular has its API for loading components dynamically.

Dynamic component loading

In the given example, we can see how to build a dynamic ad-banner.

The hero agency is planning an ad-campaign with several different ads cycling through the banner, where new ad components are added often by different teams. We need to load a new component without a fixed reference to the component in the ad banner's template.

Angular comes with its API for loading components dynamically.

Steps required to create Dynamic Component in Angular 8

  1. Create an anchor directive
  2. Loading components
  3. Resolving components
create Dynamic Component in Angular 8

Create an Anchor Directive

We should know where to include this anchor point into components. Create helper directive called NewsFeedDirective to create the anchor to insert anywhere to the component. The ad banner uses a directive called AdDirective to make a valid insertion point in the template bar.

src/app/ad.directive.ts

import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[ad-host]',
})
export class AdDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
} 

AdDirective injects ViewContainerRef to access to the view container of the element that host the dynamic added component.

In the @Directive decorator, observe the selector name, ad-host; that is, we use to apply the directive in the element.

Loading Components

Most of the ad banner implemented in ad-banner.component.ts. To keep things simple in the example, the HTML is in the @Component decorator’s template properly as a template string.

The element is where we apply the directive we just made. To ask the AdDirective, recall the selector from ad.directive.ts and ad-host. Apply the without the square brackets.

src/app/ad-banner.component.ts(template)

template: `
  

Advertisements

`

The element is good choice for dynamic component because it doesn't render any additional output.

Resolving components

In Resolving component, AdBannerComponent takes an array of AdItem objects as input, which finally comes from the AdService. AdItem objects generate the type of component to load and any data to bind in the component.AdService returns the actual ad making up the ad campaign.

Passing an array of a component to AdbannerComponent allows for a dynamic list of ads without static element in the template.

src/app/ad-banner.component.ts(excerpt)

export class AdBannerComponent implements OnInit, OnDestroy {
@Input() ads: AdItem[];
currentAdIndex = -1;
@ViewChild(AdDirective, {static: true}) 
adHost: AdDirective;
interval: any;
constructor (privatecomponentFactoryResolver: ComponentFactoryResolver)
{}
ngOnInit() {
this.loadComponent();
this.getAds(); 
}
ngOnDestroy(){
clearInterval(this.interval);
}
loadComponent(){ 
this.currentAdIndex=
(this.currentAdIndex + 1) % this.ads.length;
const adItem = this.ads[this.currentAdIndex];
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
const viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
(componentRef.instance).data = adItem.data;
}
getAds() { 
this.interval = setInterval(() => {
this.loadComponent();
}, 3000);
}
} 

After loadComponent() select an ad, it uses ComponentFactoryResolver to resolve a ComponentFactory for each particular component. The ComponentFactory creates an instance of each component.

Next, we are targeting the viewContainerRef that exists on this specific instance of the component. Because it’s referring to adHost is the directive we set up earlier to tell Angular that where to insert dynamic components.

As we may recall, AdDirective injects ViewContainerRef into its constructor. The directive accesses the element that we want to use to host the dynamic component.

To add the component in the template, we can call createComponent() on the ViewContainerRef.

The createComponent () method returns a reference into the loaded component. Use the reference to interact with the component by assigning to its properties or calling its methods.

Selector References

The Angular compiler generates a ComponentFactory for a  component referenced in a template. There are no selector references in a template. There are no selector references in the template for dynamically loaded components since they are load at the runtime.

To ensure that the compiler quiet generates a factory, add dynamically loaded components into the NgModule’s entryComponents array:

entryComponents: [ HeroJobAdComponent,HeroProfileComponent],

The AdComponent interface

In the ad-banner, all components implement a common AdComponent interface to standardize the API for passing data to the component.

hero-job-ad.component.ts

import { Component, Input } from '@angular/core';
import { AdComponent }from './ad.component';
@Component({
template: `

{{data.headline}}

{{data.body}}
  ` }) export class HeroJobAdComponent implements AdComponent { @Input() data: any; }

Output Final ad banner

It is changing in per 5 seconds so that I put all the screenshot here serially. All the screenshot came one by one like an ad-banner.

Featured hero profile
Brave as they come
Opening in all departments
Hiring for Several position

Related Topics

String Interpolation in Angular 8

String Interpolation in Angular 8 String interpolation is a one-way data-binding technique which is used to output the data from a typescript code to HTML template. It uses the template expression. It uses the...

2 minutes read.

Angular 8 NgStyle Directive

Angular 8 NgStyle Directive The ngStyle attribute is used to change and style the multiple properties of Angular. We can change the value, color, and size, etc. of the component. It is a built-in...

1 minute read.

Angular 8 App Loading

How an Angular 8 app loaded and started When we create an Angular app and run it by using ng serve command, it looks like the below screenshot. It is a simple...

3 minutes read.

History and Versions of Angular 8

Introduction to Angular JS Misko created Angular JS and the first version of Angular also name as "Angular 1". He built a framework to handle the downfalls of HTML. The first...

3 minutes read.

Angular 8 ngIf Directive

ngIf Directive is the part of structural directives.The NgIf is the most straightforward structural Directive and comfortable to understand. The ngIf Directives is used to add and remove HTML elements according to...

2 minutes read.

Angular 8 Unit Testing

What is unit testing? Unit testing is a type of software testing where individual components of the software are tested. It is done during the development of any application. A unit may be...

6 minutes read.

Node.js async.queue() Method

Node.js async.queue() Method What is Async module? In Node.js, we have an async module that has a lot of functionality, but the main use case of this module is to do multiple...

3 minutes read.

Data Binding in Angular 8

What is Binding? Binding is the process which generates the connection between the application UI and the data which comes from the business logic. In Angular, it is called the automatic synchronization of...

3 minutes read.

Angular 8 Forms

Angular forms are used to handle the user's input. We use Angular form in our application to authorize users to log in, to update profile, to enter information, and to perform many other...

3 minutes read.

Creating first APP in Angular 8

Firstly, we have to open Git Bash and, then we have to write the following command in it. ng new my -app The project has been created now so that now we have to go...

2 minutes read.

Angular 8 Pipes

Angular 8 Pipes Pipes are a useful feature in Angular. These are the simple way to transform values in an Angular template. It takes the integers, strings, array, and dates as input separated with...

3 minutes read.

Angular 8 changes and new features

The angular version number indicates the level of changes introduced by the release. The use of semantic versioning helps us understand the potential impact of updating to a new version. Angular is the...

5 minutes read.

Angular 8 Libraries

Angular libraries are built a solution of general problems like presenting a unified user interface, presenting data, and allowing the data entry. Developers can create standard solutions for particular domains...

3 minutes read.

$timeout service in AngularJS

The discipline of web development is expanding quickly. A technology that is released today will inevitably become obsolete in a few months. The webpages were static in the past and...

4 minutes read.

Scalability and Validation Forms in Angular 8

Form Validation Validation is an essential part of managing any set of forms. If we are checking for required fields or querying an external API for a username. Angular 8 provides a set of...

1 minute read.

Advantages | Disadvantages of Angular 8

Advantages of Angular 8 There are some Advantages of angular 8 which are given below: It offers clean code developmentHigher PerformanceAn angular framework can take care of routing, which...

1 minute read.

ngSwitch Directive in Angular 8

Angular 8 ng-Switch Directive The ng-Switch Directive hides and shows the HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match; otherwise, the component and...

2 minutes read.

Dependency Injection in Angular 8

Dependency injection (DI), is an essential application design pattern. Angular 8 has its own DI framework, which used in the design of Angular application to increase efficiency and portability. Dependencies are the services that...

7 minutes read.

Two-way Data Binding in Angular 8

Two-way Data Binding in Angular 8 Two-way data binding is a synchronization between the model and the view. We can use the ngModel directive in two-way data binding. Custom two-way data binding is useful...

2 minutes read.

Installation of Angular 8

Installation Guides to Angular 8 step by Step Angular combines declarative templates, dependency injection and, end to end tooling to solve development challenges. Angular empowers developers to build an application that lives on the...

4 minutes read.