Dynamically Add Component in Angular

share link

by Abdul Rawoof A R dot icon Updated: Jan 5, 2024

technology logo
technology logo

Guide Kit Guide Kit  

Components are the most basic user interface building blocks of an Angular App. A tree of Angular components. These angular additives are a subset of directives. 


A template always associates them, unlike other directives. In a template, a certain element can only instantiate one component.  


It lets us offer a manner to fashion the component. It provides different CSS styling, rules, and other device-specific style configurations. A specific component uses those. It is an unbiased and reusable little bit of code. They serve the identical cause as JavaScript functions. But they paint in isolation and go back HTML. It is available in extraordinary types. In those, one is a category component, and any other one is a useful component. 

 

Here is an example of how to add a dynamic component in AngularJS: 

Fig: Preview of the output that you will get on running this code from your IDE.

Code

@Component({
   selector: 'div[app-type=section]',
   template: ''
})
export class SectionComponent {
  @Input() active: boolean;

   constructor(public viewContainerRef: ViewContainerRef) { }
} 

@Component({
  selector: 'app-toolbar',
  template: '<button (click)="addComponentClick.emit()">Add Text component</button>'
})
export class ToolbarComponent {
  @Output() addComponentClick = new EventEmitter();
   constructor() { }
} 

import { Component, AfterViewInit, ViewChildren, QueryList, ElementRef, ComponentFactoryResolver, ComponentFactory, OnInit } from '@angular/core';
import { TextComponent } from './text.component';
import { SectionComponent } from './section.component';

@Component({
   selector: 'app-view',
   template: `<div class="container">
<app-toolbar (addComponentClick)="onAddComponentClick()"></app-toolbar>
<div app-type="section" id="SECTION1" [active]="true"></div>
<div app-type="section" id="SECTION2"></div>
</div>`
})
export class ViewComponent implements AfterViewInit, OnInit {
  @ViewChildren(SectionComponent) sections: QueryList<SectionComponent>;
  activeSections: SectionComponent[];
  textComponentFactory: ComponentFactory<TextComponent>;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {  }

  ngOnInit() {
    this.textComponentFactory = this.componentFactoryResolver.resolveComponentFactory(TextComponent);
  }

  ngAfterViewInit() {
    this.activeSections = this.sections.reduce((result, section, index) => {
      if(section.active) {
        result.push(section);
      }
      return result;
    }, []);
  }

   onAddComponentClick() {
    this.activeSections.forEach((section) => {
      section.viewContainerRef.createComponent(this.textComponentFactory);
    });
   }
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install Node and Visual Studio Code on your computer.
  2. Open terminal, install Angular using this command-'npm install -g @angular/cli@latest'.
  3. Create new folder using the command-'ng new folder_name'.
  4. Then open the folder from File->Open Folder.
  5. Need to create some additional files with the following names,
  6. section.component.ts
  7. text.component.ts
  8. toolbar.component.ts
  9. view.component.ts
  10. Copy and paste the code in the files as per in the demo(refer demo given below).
  11. Import those files in 'app.module.ts' file.
  12. Finally, remove the code from 'app.component.html' and replace with this tag "<app-view></app-view>".
  13. Save the files and open the terminal, use this command-'ng serve' to generate the output in localhost.


Note: In tsconfig.json file, change "strict":true to "strict":false.

Reference: 'DEMO'


I hope you found this helpful.


I found this code snippet by searching for 'dynamically add component in angular' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created and tested in Visual Studio Code 1.74.1.
  2. The solution is test in Angular CLI - 15.2.2.
  3. Node version 18.15.0.


Using this solution, we are able to add dynamic component in Angular with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to add dynamic component in Angular.

FAQ

1. How can I dynamically add components in Angular? 

To create and add components in Angular we can use two things: 

  • ComponentFactoryResolver 
  • ViewContainerRef 


2. What is ComponentFactoryResolver? 

To retrieve the ComponentFactory for a given component type in Angular we can use this. You can then use it to create instances of that component dynamically. 


3. How do I use ViewContainerRef for dynamic component creation? 

ViewContainerRef can attach one or more views, representing a container. You can use it to create and insert components dynamically into the view. 


4. Can I pass data to dynamically added components? 

Yes, you can pass data to dynamically added components. You can use the ComponentFactoryResolver to create an example of the component. Then, set its properties or pass data through the components. 


5. Is it possible to dynamically remove components? 

Yes, you can dynamically remove components. Use the destroy method on the ViewRef obtained from the ViewContainerRef.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.