-
Notifications
You must be signed in to change notification settings - Fork 0
/
svg-icon.component.ts
51 lines (43 loc) · 1.38 KB
/
svg-icon.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { ChangeDetectionStrategy, Component, ElementRef, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
import { BehaviorSubject, filter, Subject, switchMap, takeUntil } from 'rxjs';
import { SvgService } from '../../services';
@Component({
selector: 'svg-icon',
template: '',
styleUrls: ['./svg-icon.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SvgIconComponent implements OnChanges, OnInit, OnDestroy {
@Input()
src: string;
private readonly svgSrc = new BehaviorSubject<string>(undefined);
private readonly unsubscribe$ = new Subject<void>();
constructor(
private elementRef: ElementRef<HTMLElement>,
private svgService: SvgService,
) {}
ngOnChanges(changes: SimpleChanges): void {
if ('src' in changes) {
this.svgSrc.next(this.src);
}
}
ngOnInit(): void {
this.svgSrc
.pipe(
filter(Boolean),
switchMap(() => this.svgService.isInitialized$),
filter(Boolean),
takeUntil(this.unsubscribe$),
)
.subscribe(() => this.loadSvg(this.src));
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
private loadSvg(src: string): void {
const svgElement = this.svgService.getSvg(src);
this.elementRef.nativeElement.innerHTML = null;
this.elementRef.nativeElement.appendChild(svgElement);
}
}