Project

General

Profile

1 61381 k.triantaf
import {Directive, ElementRef, Input, OnInit, Renderer2} from "@angular/core";
2
3
@Directive({
4
  selector: '[svg-background]',
5
})
6
export class SvgBackgroundDirective implements OnInit{
7
  @Input()
8
  private color: string;
9
  @Input()
10
  private svg: string;
11
  @Input()
12
  private svgColor: string;
13
  @Input()
14
  private position: string = null;
15
  private readonly element: any;
16
17
  constructor(private elementRef: ElementRef,
18
              private renderer: Renderer2,) {
19
    this.element = this.elementRef.nativeElement;
20
  }
21
22
  ngOnInit() {
23
    let svg = this.encodeSvg();
24
   if(this.position && svg) {
25
     this.renderer.setStyle(this.element, 'background', "url(" + svg + ") " + (this.color?this.color + " ":"") + "no-repeat " + this.position);
26
   }
27
  }
28
29
  private encodeSvg(): string {
30
    if(this.svg && this.svgColor) {
31
      return 'data:image/svg+xml,' + encodeURIComponent(this.svg.replace('{{color}}', this.svgColor));
32
    }
33
    return null;
34
  }
35
}