I am working on an Angular 12 application and I want to create a custom directive for links that adds an external link icon (svg) after the link. Here is an example: https://i.sstatic.net/bOzB9.png
The usage of the directive would look like this:
<a externalLink [href]="url">View in Jira</a>
So far, I have not been able to programmatically insert an svg or an icon. One potential solution could be using `ComponentFactoryResolver` to dynamically create an icon component from our component library. Another option might be creating an svg element directly and appending it to the DOM. However, I have not successfully implemented either method yet, so any suggestions or tips are welcome! :)
I believe implementing this functionality as a directive would be cleaner and more lightweight, but I am open to considering creating it as a component if that simplifies the process. Please let me know if and how it's possible to achieve this using a directive.
This is what my directive looks like currently:
import { ComponentFactory, ComponentFactoryResolver, Directive, ElementRef, HostBinding, OnInit, Renderer2, TemplateRef, ViewContainerRef } from '@angular/core';
import { CustomIcon } from '@company/components-lib/custom-icon';
@Directive({
selector: 'a[externalLink]',
})
export class ExternalLinkDirective implements OnInit {
@HostBinding('attr.target') readonly target = '_blank';
svgContent = '';
constructor(
private el: ElementRef,
private renderer: Renderer2,
private componentFactory: ComponentFactory<unknown>,
private readonly templateRef: TemplateRef<unknown>,
private readonly viewContainer: ViewContainerRef,
private readonly componentFactoryResolver: ComponentFactoryResolver
) {
}
ngOnInit(): void {
this.svgContent =
`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">`+
`<path d="M18.75 11.8869V18.75H5.25V5.25H12.1131L9.86306 3H3.75C3.33577 3 3 3.33581 3 3.75V20.25C3 20.6642 3.33577 21 3.75 21H20.25C20.6642 21 21 20.6642 21 20.25V14.1369L18.75 11.8869V11.8869Z" fill="#3ad4dd" />`+
`<path d="M13.0449 3L15.9617 5.9168L9.87854 12L11.9999 14.1213L18.0831 8.03812L20.9999 10.955V3H13.0449Z" fill="#3ad4dd" />`+
`</svg>`;
let svg = this.renderer.createElement('svg');
this.renderer.setAttribute(svg, 'innerHTML', this.svgContent);
let parent = this.renderer.parentNode(this.el.nativeElement);
parent.appendChild(svg);
}
}