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.

Animate Dynamic Components In Angular

  • By Gokulaselvan
  • May 11, 2020
  • 1271 Views

The blog intends to illustrate the way how the components can be loaded dynamically in Angular. In this internet world, data is generated in huge volumes every minute, static development is no more sufficient to satisfy today needs.
In terms of front end perspective, one cannot develop applications that can adapt to all the data sources. There are a variety of data, and each needs its own style of presentation. If this is the case, think of developing separately and placing the components in the container page might not be the best solution.
Handling this use case in Angular is straightforward since Angular provides API for dynamic component loading.
Two important classes:

  • ComponentFactoryResolver
  • ComponentFactory

ComponentFactoryResolver provides the factory for the given component, and with the factory’s create method, the component can be created dynamically.
Let’s walk through an example that shows creating dynamic components with different data. We will use sample news articles and create dynamic components for each section.
In this example, we look into two components – NewsContainerComponent and NewsDetailsComponent. NewsContainerComponent is the container that holds the links for all the news articles, and also the dynamic NewsDetailsComponent is placed here.

Also Read

Angular Material: Build Your Own Generic MatTable

Service File

export class NewsInfoService {
 latestNews: NewsStructure[] = [
   {headline: 'Covid 19 World', detail: 'WHO has updated operational...',     image: 'assets/images/who.png'},
   {headline: 'Covid treatment', detail: 'Among patients who have been...' , image: 'assets/images/corona.jpg'},
   {headline: 'Covid Updates', detail: 'India\'s plans of mass screening...', image: 'assets/images/covid_update.jpg'}
 ];
 constructor() { }
 getNews() {
   return this.latestNews;
 }
}

Three news data is defined for our example, and the getNews() method will return all the news.
NewsStructure is just an interface that we have defined to maintain a structure for the news articles.

export interface NewsStructure {
 headline: string;
 detail: string;
 image: string;
}

NewsContainerComponent

import { Component, OnInit, ViewChild, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { NewsStructure } from '../news-structure.component';
import { NewsInfoService } from '../news-info/news-info.service';
import { NewsDetailsComponent } from '../news-details/news-details.component';
@Component({
 selector: 'app-news-container',
 template: `
   <div class="news-list">
     <ul>
       <li *ngFor="let news of newsList" (click)="loadDetailsComponent(news)">
         {{news.headline}}
       </li>
     </ul>
   </div>
   <ng-template #newsDetail></ng-template>
 `
})
export class NewsContainerComponent implements OnInit {
 newsList: NewsStructure[] = [];
 @ViewChild('newsDetail', {read: ViewContainerRef}) containerRef: ViewContainerRef;
constructor(
   private newsService: NewsInfoService,
   private factoryResolver: ComponentFactoryResolver) { }
 ngOnInit() {
   this.newsList = this.newsService.getNews();
 }
 loadDetailsComponent(news) {
   const componentFactory =    this.factoryResolver.resolveComponentFactory(NewsDetailsComponent);
   this.containerRef.clear();
   const componentRef = this.containerRef.createComponent(componentFactory);
   (<NewsDetailsComponent>componentRef.instance).newsInfo = news;
 }
}

 
Take a closer look at the above code. We get all the news articles from the service file and assign it to the newsList property. In the template, we loop through the articles to create a link for each news with *ngFor directive.

<ng-template #newsDetail></ng-template>

#newsDetail is the template reference variable, which is the reference place to display the components that will be created dynamically.

@ViewChild('newsDetail', {read: ViewContainerRef}) containerRef: ViewContainerRef;

@ViewChild is a property decorator that query elements from DOM. Here we query an element with #newsDetail as ViewContainerRef.
Already links were created for each news article, and when a link is clicked, the loadDetailsComponent() is invoked with the corresponding news data. This method holds the actual logic of creating dynamic components.
First, the factory is created for the NewsDetailsComponent with ComponentFactoryResolver
The factory is then passed to the createComponent() method of ViewContainerRef, and this creates the component.
To the instance of the created component, the corresponding news data is passed.

NewsDetailsComponent

import { Component, OnInit, Input } from '@angular/core';
import { NewsStructure } from '../news-structure.component';
@Component({
 selector: 'app-news-details',
 template: `
  <div class="news-report">
    <div><img [src]="newsInfo.image"></div>
    <div>
      <h2>{{newsInfo.headline}}</h2>
      <p>{{newsInfo.detail}}</p>
    </div>
  </div>
 `
})
export class NewsDetailsComponent implements OnInit {
 @Input() newsInfo: NewsStructure;
 constructor() { }
 ngOnInit() {
 }
}

In this component, the newsInfo input property receives the data passed from the container component and displays the news detail and image.
To animate, simple fade-in animation is applied when the dynamic component is rendered in the template.

.news-report {
  animation: fade-in 1.2s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
}
@keyframes fade-in {
 0% { opacity: 0; }
 100% { opacity: 1; }
}

Output

dynamic-components-angular

EndNote

The example illustrated in this blog is a simple to use case to help you easily understand the base concept. Here, we changed the data for each news article and maintained a definite style of presentation, but in real situations, each news demands varied display and layout. In such use cases, dynamic components are predominately used as the best practice. One cannot create separate components for each news in advance, this leads us to the concept of dynamic rendering.
Looking to develop your application with Angular? Hire Angular developers today at Agira technologies. Get in touch with our Angular experts to get started!

Turn your vision to magnificent reality With
Our Web and Mobile Solutions

Gokulaselvan

Gokulaselvan is a software developer. He is specializing in front end frameworks such as Angular, and React. He is a passionate techie with great fondness towards problem-solving in reactive programming. You can find him browsing and exploring different trends or either searching for easier ways to solve a problem. Gokul loves to share his new learning with others.