Dynamic Component Loader (Angular)
Inject any component you want! (There are a few stories like this, but they’re unfortunately outdated or doesn’t contemplate Input() and Output())
Last week during a sprint planning i’ve caught myself thinking and rethinking good ways to deliver the best code possible.
I’m heavly involved in a new product and that got my batteries are totally recharged!
Generic components are things that really hook me, i’m always wondering:
“.. that’s a nice code, hm how i can reuse all of this elsewhere? ”, that’s exactly what i thought after coding and styling a Dialog(tbh, it was very good looking).
How can i recycle all these headers and footers?
For learning purposes, i choose to build a generic component that SHOULD represent an iPhone main screen with four apps at the bottom tray.
The icons aren’t the same, nor the apps layout, this layout DOES NOT REPRESENT MY CSS SKILLS! 👀
Instead of putting all the four apps and hide/show them using *ngIf i rather use dynamic component loading to avoid triggering the *ngIf for each component.
The phone number
(703)521–7859 was passed via Input() and the Output() was responsible for emiting which number is being called (and pop the calling dialog).
I won’t show any code here, if you want to see the code behind the gif, there is a stackblitz and a github repo waiting for you. (It’s on easy mode, so won’t take more than 15 seconds to open them and copy paste wherever you want.)
My goal here was to present a different approach to solve a problem that may appear on a daily basis situation.
PLEASE, CLICK AND TRY THE CODE!
Quick explanation
You gotta create a tag with a template reference
<ng-template #dynamic></ng-template>
Access using a ViewChild
@ViewChild('dynamic', { read: ViewContainerRef, static: true }) viewContainerRef: ViewContainerRef;
And run the code bellow, no big deal!
// Creates a factory with the component you choose
const factory = this.factoryResolver.resolveComponentFactory(component);// Clear the reference (in case of having another component/anything else there before)
this.viewContainerRef.clear();// Create the component(he is inside the factory) into the reference
const componentDy = this.viewContainerRef.createComponent<any>(factory);