angulartypescriptinterface

How to inject component dynamically based on data type?


I have different sections od the applications (I am using standalone components so don't want to say modules). I dont want to have direct dependencies between sections.

Now, one of the sections is search. When user does a search, different search result types can be shown. Let's say searchResultType1, searchResultType2, searchResultType3 (they are search result item components). All of them can be shown at once in the list, mixed. They are shown using ngFor in a template.

Each searchResultTypeX is implemented in its corresponding section of the app.

I am thinking defining abstract class that all searchResultX types implement but they are all injected into search component as abstract class.

I know how to implement this when I have one, but can't figure out if there is a way to inject all of them based on data type returned by search.


Solution

  • There's no way for angular to inject those components automatically. However, you can load those component dynamically. For that you can create some component factory, and use NgComponentOutlet to render components - https://angular.io/guide/dynamic-component-loader

    Here's stackblitz with example how to do it https://stackblitz.com/edit/angular-dnfg41?file=src%2Fsolution-with-factory.component.ts

    I made factory method, but it would be probably best to have it in separate class.

    If you need to pass some inputs for the component, you can also do it through NgComponentOutlet. You could modify the factory to return object {componentType, inputs}, and later pass both to NgComponentOutlet