openaire-library/utils/svg-background/svg-background.directive.ts

36 lines
956 B
TypeScript

import {Directive, ElementRef, Input, OnInit, Renderer2} from "@angular/core";
@Directive({
selector: '[svg-background]',
})
export class SvgBackgroundDirective implements OnInit{
@Input()
private color: string;
@Input()
private svg: string;
@Input()
private svgColor: string;
@Input()
private position: string = null;
private readonly element: any;
constructor(private elementRef: ElementRef,
private renderer: Renderer2,) {
this.element = this.elementRef.nativeElement;
}
ngOnInit() {
let svg = this.encodeSvg();
if(this.position && svg) {
this.renderer.setStyle(this.element, 'background', "url(" + svg + ") " + (this.color?this.color + " ":"") + "no-repeat " + this.position);
}
}
private encodeSvg(): string {
if(this.svg && this.svgColor) {
return 'data:image/svg+xml,' + encodeURIComponent(this.svg.replace('{{color}}', this.svgColor));
}
return null;
}
}