I am working on an Angular project where I need to dynamically load different components based on API data. The home page consists of a banner and a news section. Instead of having the banner always at the top and the news section at the bottom, I want to load these components multiple times with different data based on what is fetched from the database.
In the home.component.ts
file, I have the following code:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { AccountServiceProvider} from '../../providers/account-service/account-service';
@Component({
selector : 'app-home',
templateUrl : './home.component.html',
styleUrls : ['./home.component.scss'],
encapsulation : ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
public banner : any;
public news : any;
constructor( private accountService : AccountServiceProvider ) {
/* Data is fetched from WordPress API; client can choose either banner first or news first */
this.accountService.getStartPageData().then( ( response: any ) => {
for ( let entry of response ) {
if ( 'banner_block' === entry.acf_fc_layout ) {
this.banner = entry;
}
if ( 'news_block' === entry.acf_fc_layout ) {
this.news = entry;
}
}
});
}
ngOnInit() {
}
}
The home.component.html
, banner.component.ts
, and news.component.ts
files contain the template and logic for loading the banner and news components dynamically according to the data received.
Instead of statically adding these components, I want to dynamically load them based on the data. I am currently researching solutions on how to achieve this, including the possibility of loading component HTML in the component TypeScript file. However, I have not yet found a definitive answer.