At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

How To Build Dynamic Components In Angular 6

  • By Manikandan Thangaraj
  • September 24, 2018
  • 893 Views

 

Dynamic components are one of the versatile and core concepts introduced in Angular, this will greatly help the developers to render a component dynamically during run time. The component templates are not always fixed sometimes we may need to load the new component at run-time in various scenarios. So, in this article, let’s have a deep look into the process of creating dynamic component with simple steps,

The following example shows how to build a dynamic news feed.
Let’s assume we have one application to display the different news feed dynamically and news feeds will be loaded with frequent updates. It cannot be simply achieved with static component so here’s where the dynamic component comes in to make it possible.
The good news is that Angular has its very own API for loading components dynamically so let’s see how to create this dynamic component now,

Steps Required To Create Dynamic Component In Angular,

 

  1. Create an anchor directive
  2. Loading components
  3. Resolving components

 

Create An Anchor Directive

To define the anchor point, We should let the angular know where to include this anchor point into components. Here we’re going to create helper directive called NewsFeedDirective to create the anchor to insert anywhere into the components. This directive will handle the insertion of NewsFeed.
You can find the path here,
src/app/newsfeed.directive.ts

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

NewsFeedDirective injects ViewContainerRef for gaining the access to view the container of the element that will host the dynamically added component.
In the @Directive decorator, you can notice the selector name mentioned as “news-feed” which is used to apply the directive to the element.

Best To Read: Angular 6: Upgrading & Summary of New Features

 

Loading Components:

Most of the implementation of newsfeed will goes into newsfeed.component.ts. In below sample i have used the <ng-template> where all the elements will be directly added on the newsfeed directive which we created earlier. To add NewsFeedDirective just add the selector “news-feed” to the <ng-template>. By Adding this, angular will come to know where to insert the new newsfeed.
You can see the file path here,
src/app/newsfeed.component.ts (template)

template: `
           <div class="newsfeed">
             <h3>News Feed</h3>
             <ng-template news-feed></ng-template>
           </div>`

 

Resolving Components

See the methods in news-feed.component.ts.
NewsFeedComponent takes an NewsFeedItem objects as input served by NewsFeedService. NewsFeedItem is an array of objects, it will specify what type of the component to load and what data we should bind in the component.
With use of getAds() method in NewsFeedService, NewsFeedComponent taking an array of components to load the dynamic list of newsfeed without any static templates.
NewsFeedComponent will loop through the array of NewsFeedItem and it loads a fresh template for every 3 seconds by calling loadNewsFeedComponents().

src/app/news-feed-banner.component.ts
export class NewsFeedBannerComponent implements OnInit, OnDestroy {
 @Input() newsfeeds: NewsFeedItem[];
 currentAdIndex = -1;
 @ViewChild(NewsFeedDirective) newsfeed: NewsFeedDirective;
 interval: any;
 constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
 ngOnInit() {
   this.loadNewsFeedComponents();
   this.getNewsFeeds();
 }
 ngOnDestroy() {
   clearInterval(this.interval);
 }
 loadNewsFeedComponents() {
   this.currentAdIndex = (this.currentAdIndex + 1) % this.newsfeeds.length;
   let NewsFeedItem = this.newsfeeds[this.currentAdIndex];
   let componentFactory = this.componentFactoryResolver.resolveComponentFactory(NewsFeedItem.component);
   let viewContainerRef = this.newsfeed.viewContainerRef;
   viewContainerRef.clear();
   let componentRef = viewContainerRef.createComponent(componentFactory);
   (<NewsFeedComponent>componentRef.instance).data = NewsFeedItem.data;
 }
 getNewsFeeds() {
   this.interval = setInterval(() => {
     this.loadNewsFeedComponents();
   }, 3000);
 }
}

The loadNewsFeedComponents() will perform more things to get it done so will go through step by step now,

  1. It will get the news feeds as a “NewsFeedItem object array” from NewsFeedsService.
  2. Next, it will select the news feed and it will resolve a ComponentFactory for specific component using ComponentFactoryResolver . Then the ComponentFactory will start creating instance for each components.
  3. NewsFeedDirevtive will inject the ViewContainerRef into constructor and this will help us to access the element that we want to use as a dynamic component.
  4. Here we are using createComponent() to add component into template. This method returns a reference of the loaded component and using that reference we have interacted with the component for accessing its properties and methods.

Angular compiler will generate a ComponentFactory for any component but it won’t create any selector references for any dynamically loaded components until those components are loaded at runtime. We can also tell angular compiler to generate the component factory for dynamic components by adding in “entryComponents” which is added into NgModule’s at src/app/app.module.ts.
[code]
entryComponents: [ JobFeedComponent, ProfileFeedComponent ]
[/code]

Learn To Secure Node.js RESTful APIs With JSON Web Tokens

 

The NewsFeedComponent Interface

All the NewsFeed components will implement a common NewsFeedComponent interface to standardize the API for passing data to the components.
[code]
export interface NewsFeedComponent {
data: any;
}
[/code]
The news feed will look like this,
Dynamic Component Loader
As i mentioned earlier, the news feed will change for every 3 second and if you want the complete coding i have used then you can get it here https://github.com/agiratech/dynamic-component-loader so try it by yourself and post us your queries if any doubts, we ll surely try to help you out. Similarly If you’re the readahloic like us? then never miss out anything from our largest blog portal where you can get continuous blog updates & latest posts about all latest technologies which would be perfect for your 15 minutes tea break! And in case if you’re a newbie then don’t forget to subscribe us to get the latest updates from diverse technologies. Hit the subscribe link and start getting the frequent updates from us straight to your inbox.
For more inquires reach us via info@agiratech.com

Manikandan Thangaraj

A Passionate full stack developer with 9 years of experience in full stack web application development and expertise in technologies like PHP and Angular. He has huge craze in learning new things about technologies and constantly shares his knowledge with others.