Friday, 11 September 2020

Angular dynamically create component

 HTML

                                    <ng-template

                                        #sampleReferenceComponent>

                                    </ng-template>



Component.ts

        // This component must be added as entrycomponent (as it is dynamically created in code not rendered as a component tag<app-comp> in html)

@import{sampleReferenceComponent}....

       import {

    Component, OnInit, OnDestroy, ViewContainerRef, ElementRef,

    ViewChild, ComponentRef, ComponentFactoryResolver, HostListener,

    Renderer2,

} from '@angular/core';


    // Container

    @ViewChild('sampleReferenceComponent', { static: false, read: ViewContainerRef })

    private sampleReferenceComponentContainer: ViewContainerRef;

    

    // Component ref

    private sampleReferenceComponentRef

        : ComponentRef<sampleReferenceComponent>;


   // Component ref subscrption

    private sampleReferenceComponentSub: Subscription;



// Dynamically create component at container(created component will show at the viewChild location in HTML)

this.sampleReferenceComponentRef =  this.sampleReferenceComponentContainer.createComponent(

                this.resolver.resolveComponentFactory(sampleReferenceComponent),

            );


// reference to public varaibles in the component including input and output

this.sampleReferenceComponentRef.instance.varaiable

this.sampleReferenceComponentRef.instance.output

this.sampleReferenceComponentRef.instance.input


// Output subscription

this.sampleReferenceComponentSub = this.this.sampleReferenceComponentRef.instance.output.subscribe(...)



// Remove created component


this.sampleReferenceComponentContainer.clear();

this.sampleReferenceComponentSub.unsubscribe();

this.sampleReferenceComponentRef.destroy();

this.sampleReferenceComponentRef = null;

No comments:

Post a Comment