After exploring numerous blog posts and discussions, I have yet to discover a solution for my template dilemma. The issue revolves around our straightforward icon component, where users can specify the desired icon and size directly in the template:
import {Component, Input} from '@angular/core';
@Component({
selector: 'comp-icon',
template: `
<span class="{{ class }}" *ngIf="icon === 'error'" >
<svg [attr.height]="size" viewBox="0 0 48 48" [attr.width]="size" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>
</span>
<span class="{{ class }}" *ngIf="icon === 'success'" >
<svg [attr.height]="size" viewBox="0 0 48 48" [attr.width]="size" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>
</span>
`
})
export class IconComponent {
@Input() icon: string;
@Input() size: number;
@Input() class: string;
constructor() {
}
}
The challenge lies in the repetitive nature of this setup and the need to incorporate custom SVG images from various applications using the library that employs this component. My current approach aims to convey the intended functionality like so:
import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {Icons} from './icons';
@Component({
selector: 'comp-icon',
template: `
<span class="{{ class }}">
<ng-container [ngTemplateOutlet]="iconContent"></ng-container>
</span>
`
})
export class IconComponent implements OnInit {
@Input() icon: string;
@Input() size: number;
@Input() class: string;
@ViewChild('iconContent') iconContent: any;
constructor() {
}
ngOnInit() {
this.iconContent = (Icons.find(icon => icon.name === this.icon) || { name: '', content: '' }).content;
}
}
Furthermore, the icons.ts file outlines the structure:
export interface IIcon {
name: string;
content: string;
}
export const Icons: IIcon[] = [
{
name: 'error',
content: `<svg [attr.height]="{SIZE}" [attr.width]="{SIZE}" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg">
</svg>`
},
{
name: 'success',
content: `<svg [attr.height]="{SIZE}" [attr.width]="{SIZE}" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg">
</svg>`
},
];
Is it feasible to dynamically alter the contents of a component section, particularly an SVG element, using this method? While I've heard about directives that could potentially help, I haven't quite grasped how to implement them effectively.