Friday, 4 February 2022

Angular 8 static and dynamic elemet reference

https://stackoverflow.com/questions/45027331/angular2-how-to-trigger-click-event-without-clicking 

static element reference :

.html

<div #myDiv>

</div>

Component:

// Read means reading an element, static true meaning element is already in template 
@ViewChild('myDiv', { read: ElementRef, static: true }) myDiv: ElementRef,
//Trigger click

  this.myDiv.nativeElement.click();

dynamic element reference :

html:

<ng-template #dynamicComponentContainer> </ng-template>

component:
import{DynamicComponentToCreate}...
// Children component reference @ViewChild('dynamicComponentContainer', { static: false, read: ViewContainerRef, }) private dynamicComponentContainer: ViewContainerRef; private dynamicComponentRef: ComponentRef<DynamiComponentToCreate>; private dynamicComponentSub: Subscription;

// To create
this.dynamicComponentRef= this.dynamicComponentContainer.createComponent( this.resolver.resolveComponentFactory( DynamiComponentToCreate ) ); // set input this.dynamicComponentRef.instance.myInput

// set output subscription
this.dynamicComponentSub= this.dynamicComponentRef.instance.output.subscribe()

// To destory
// Unsubscribe this.dynamicComponentSub.unsubscribe(); // Destroy this.dynamicComponentRef.destroy(); // Clear the container this.dynamicComponentContainer.clear(); // Reset this.dynamicComponentRef = null;

No comments:

Post a Comment