Angular Interview Questions

34 Questions
Angular

Angular

FrontendWeb Development

Question 31

How do you implement dynamic components in Angular?

Answer:

Implementing dynamic components in Angular involves creating components at runtime, which can be very useful for scenarios where the components to be displayed are not known at compile time or need to be generated based on user interactions or data fetched from a server. Angular provides tools and APIs to facilitate the creation and injection of dynamic components.

Steps to Implement Dynamic Components in Angular:

  1. Create a Placeholder for Dynamic Components:

    • Use ng-template to create a placeholder in the template where the dynamic component will be inserted.
    • Example:
      <ng-template #dynamicComponentContainer></ng-template>
  2. Define the Dynamic Component:

    • Create the component that you want to load dynamically.
    • Example:
      import { Component } from '@angular/core';
      
      @Component({
        selector: 'app-dynamic-component',
        template: `<div>Dynamic Component Loaded</div>`
      })
      export class DynamicComponent {}
  3. Create a Component to Host the Dynamic Component:

    • Create a host component with a ViewChild reference to the ng-template.
    • Example:
      import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from '@angular/core';
      import { DynamicComponent } from './dynamic.component';
      
      @Component({
        selector: 'app-host-component',
        template: `<ng-template #dynamicComponentContainer></ng-template>`
      })
      export class HostComponent {
        @ViewChild('dynamicComponentContainer', { read: ViewContainerRef, static: true }) container: ViewContainerRef;
      
        constructor(private resolver: ComponentFactoryResolver) {}
      
        loadComponent() {
          const factory = this.resolver.resolveComponentFactory(DynamicComponent);
          const componentRef = this.container.createComponent(factory);
        }
      }
  4. Trigger the Dynamic Component Loading:

    • Provide a way to trigger the loading of the dynamic component, such as a button click.
    • Example:
      <button (click)="loadComponent()">Load Dynamic Component</button>
      <ng-template #dynamicComponentContainer></ng-template>
  5. Ensure the Host Component is Included in a Module:

    • Ensure that both the host component and dynamic component are declared in an Angular module.
    • Example:
      import { NgModule } from '@angular/core';
      import { BrowserModule } from '@angular/platform-browser';
      import { HostComponent } from './host.component';
      import { DynamicComponent } from './dynamic.component';
      
      @NgModule({
        declarations: [
          HostComponent,
          DynamicComponent
        ],
        imports: [
          BrowserModule
        ],
        entryComponents: [DynamicComponent], // Add dynamic component here
        bootstrap: [HostComponent]
      })
      export class AppModule {}

Example Workflow for Implementing Dynamic Components:

  1. Create the Dynamic Component:

    • Define the component that will be loaded dynamically.
      import { Component } from '@angular/core';
      
      @Component({
        selector: 'app-dynamic',
        template: `<div>I am a dynamic component!</div>`
      })
      export class DynamicComponent {}
  2. Create the Host Component:

    • Define the host component that will load the dynamic component.
      import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
      import { DynamicComponent } from './dynamic.component';
      
      @Component({
        selector: 'app-host',
        template: `
          <button (click)="loadComponent()">Load Dynamic Component</button>
          <ng-template #dynamicContainer></ng-template>
        `
      })
      export class HostComponent {
        @ViewChild('dynamicContainer', { read: ViewContainerRef, static: true }) container: ViewContainerRef;
      
        constructor(private resolver: ComponentFactoryResolver) {}
      
        loadComponent() {
          const factory = this.resolver.resolveComponentFactory(DynamicComponent);
          this.container.clear();
          this.container.createComponent(factory);
        }
      }
  3. Include Components in a Module:

    • Ensure both components are declared in an Angular module and the dynamic component is listed in entryComponents.
      import { NgModule } from '@angular/core';
      import { BrowserModule } from '@angular/platform-browser';
      import { HostComponent } from './host.component';
      import { DynamicComponent } from './dynamic.component';
      
      @NgModule({
        declarations: [
          HostComponent,
          DynamicComponent
        ],
        imports: [
          BrowserModule
        ],
        entryComponents: [DynamicComponent],
        bootstrap: [HostComponent]
      })
      export class AppModule {}

Advanced Usage: Passing Data to Dynamic Components

You can also pass data to dynamically created components by using ComponentRef.

  1. Modify the Dynamic Component to Accept Input:

    • Define an @Input property in the dynamic component.
      import { Component, Input } from '@angular/core';
      
      @Component({
        selector: 'app-dynamic',
        template: `<div>{{data}}</div>`
      })
      export class DynamicComponent {
        @Input() data: string;
      }
  2. Pass Data When Creating the Component:

    • Set the input property when creating the component dynamically.
      import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
      import { DynamicComponent } from './dynamic.component';
      
      @Component({
        selector: 'app-host',
        template: `
          <button (click)="loadComponent()">Load Dynamic Component</button>
          <ng-template #dynamicContainer></ng-template>
        `
      })
      export class HostComponent {
        @ViewChild('dynamicContainer', { read: ViewContainerRef, static: true }) container: ViewContainerRef;
      
        constructor(private resolver: ComponentFactoryResolver) {}
      
        loadComponent() {
          const factory = this.resolver.resolveComponentFactory(DynamicComponent);
          this.container.clear();
          const componentRef = this.container.createComponent(factory);
          componentRef.instance.data = 'Hello from Host Component';
        }
      }

In Summary:

Dynamic components in Angular allow you to create and insert components at runtime. This involves setting up a placeholder using ng-template, defining the dynamic component, creating a host component to load the dynamic component, and configuring Angular to support these dynamic operations. Advanced scenarios may include passing data to dynamic components and managing their lifecycle more precisely. By leveraging Angular’s APIs and features, you can create flexible and dynamic user interfaces that respond to runtime conditions and user interactions.

Recent job openings