bhansa
bhansa

Reputation: 7534

Loading dynamic component from array angular

I want to load some angular svg components which are specified in an array. For example in below code I want to load TwitterLogo and YoutubeLogo in another component.

TwitterLogo and other is a svg component

//twitter-logo.component.svg

<svg id="twitter-logo" height="24" data-name="Logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">
    <rect width="400" height="400" fill="none"/>
    <path d="M153.62,301.59c94.34,0,145.94-78.16,145.94-145.94,0-2.22,0-4.43-.15-6.63A104.36,104.36,0,0,0,325,122.47a102.38,102.38,0,0,1-29.46,8.07,51.47,51.47,0,0,0,22.55-28.37,102.79,102.79,0,0,1-32.57,12.45,51.34,51.34,0,0,0-87.41,46.78A145.62,145.62,0,0,1,92.4,107.81a51.33,51.33,0,0,0,15.88,68.47A50.91,50.91,0,0,1,85,169.86c0,.21,0,.43,0,.65a51.31,51.31,0,0,0,41.15,50.28,51.21,51.21,0,0,1-23.16.88,51.35,51.35,0,0,0,47.92,35.62,102.92,102.92,0,0,1-63.7,22A104.41,104.41,0,0,1,75,278.55a145.21,145.21,0,0,0,78.62,23" fill="#fff"/>
</svg>

//svg-constant.module.ts

import { NgModule } from '@angular/core';
import { TwitterLogo } from './twitter-logo.component';
import { YoutubeLogo } from './youtube-logo.component';

@NgModule({
    declarations: [TwitterLogo, YoutubeLogo]
})
export class SVGConstant{
    public iconsArray = [
        {
            iconName: 'twitter',
            iconComponent: TwitterLogo
        },
        {
            iconName: 'youtube',
            iconComponent: YoutubeLogo
        }
    ];
}

I want to load these in app component like this:

//app.component.html

<div *ngFor="let icon of iconsArray">
    {{icon.iconComponent}}
</div>
//app.component.ts

import { Component } from '@angular/core';
import { SVGConstant } from './svg/svg-constant.module';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'svg-solution';
  public iconsArray;
  constructor(svgConstant: SVGConstant){
    this.iconsArray = svgConstant.iconsArray;
  }
}

Problem:

On page it is loading like this:

class TwitterLogo { }
class YoutubeLogo { } 

Instead I want to load the svg component.

Upvotes: 0

Views: 375

Answers (1)

TotallyNewb
TotallyNewb

Reputation: 4820

An extremely similar use case is very well documented in the official docs here, so I won't go into details explaining the details.

At the beginning of the guide there's even a link to a working stackblitz and a link to a zipped project if the stackblitz is down.

Upvotes: 1

Related Questions