As I develop my website, I am faced with the challenge of incorporating multiple components. One specific feature involves allowing users to dynamically add a component of their choice to the "Home" page when they click a button. I have explored three different methods for achieving this functionality and now seek guidance on determining the best practice for implementing such a feature. The initial setup of the page will include components added by previous users, with the ability for new users to contribute additional components.
The Angular framework recommends utilizing dynamic component loading: https://angular.io/guide/dynamic-component-loader
On the other hand, Angular Material suggests using CDK Portals to handle this process: https://material.angular.io/cdk/portal/overview
Personally, I initially approached this problem in a way that I found effective but am unsure if it aligns with best practices:
In my approach, clicking on a particular tag triggers an append method:
<a class="dropdown-item" href="#!" (click)="prependMedia('elementOne')">ElementOne</a>
This method is defined in the TypeScript file of the component, where a new element is added to an array when called. The corresponding HTML watches for any new elements added to display the component within an ngFor loop:
TypeScript File:
mediaElements: any[] = [];
element: any = {
name: 'elementOne',
data: 'data'
};
constructor() { }
ngOnInit() {}
prependMedia(type: string) {
console.log(type);
this.mediaElements.push(this.element);
}
HTML File displaying the component once added to the mediaElements array:
<div *ngFor="let element of mediaElements" [(ngModel)]="mediaElements">
<div *ngIf="element.name == 'elementOne'">
<app-elementone></app-elementone>
</div>
</div>
My query revolves around identifying any technical flaws in my current method of utilizing ngFor. Furthermore, I seek objective insights into the most efficient way to add a component to the DOM upon user interaction. I am particularly interested in understanding the rationale behind the preferred approach based on solid technical or Angular team-backed evidence.
While I originally leaned towards my own implementation, the discovery of Angular's recommended methodology and Angular Material's alternative approach has prompted me to reassess and opt for the most effective solution supported by factual reasoning.
I value technical advice over subjective opinions to ensure a sound decision-making process. Should you require additional context, please do not hesitate to reach out.
Thank you, Eric