要在Angular中重新加载预加载的SVG,你可以使用Angular的动态组件加载功能来实现。下面是一个示例解决方案的代码:
svgUrl: string = 'assets/icons/my-icon.svg';
img
标签来加载SVG:
SvgLoaderService
,用于重新加载SVG:import { Injectable, ComponentFactoryResolver, ViewContainerRef, ComponentRef, Type } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SvgLoaderService {
private componentRef: ComponentRef;
constructor(private resolver: ComponentFactoryResolver) { }
loadSvg(svgUrl: string, container: ViewContainerRef, componentType: Type): Promise {
return new Promise((resolve, reject) => {
const factory = this.resolver.resolveComponentFactory(componentType);
container.clear();
const componentRef = container.createComponent(factory);
const img = new Image();
img.onload = () => {
componentRef.instance.svgUrl = svgUrl;
componentRef.changeDetectorRef.detectChanges();
this.componentRef = componentRef;
resolve();
};
img.onerror = () => {
reject();
};
img.src = svgUrl;
});
}
reloadSvg(svgUrl: string): Promise {
return new Promise((resolve, reject) => {
if (this.componentRef) {
const img = new Image();
img.onload = () => {
this.componentRef.instance.svgUrl = svgUrl;
this.componentRef.changeDetectorRef.detectChanges();
resolve();
};
img.onerror = () => {
reject();
};
img.src = svgUrl;
} else {
reject();
}
});
}
}
SvgLoaderService
并使用它来加载和重新加载SVG:import { Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { SvgLoaderService } from './svg-loader.service';
@Component({
selector: 'app-svg-component',
template: `
`,
})
export class SvgComponent implements OnInit {
@ViewChild('svgContainer', { read: ViewContainerRef }) svgContainer: ViewContainerRef;
constructor(private svgLoaderService: SvgLoaderService) { }
ngOnInit() {
this.loadSvg();
}
loadSvg() {
this.svgLoaderService.loadSvg(this.svgUrl, this.svgContainer, MySvgComponent)
.then(() => {
console.log('SVG loaded successfully!');
})
.catch(() => {
console.error('Failed to load SVG.');
});
}
reloadSvg() {
this.svgLoaderService.reloadSvg(this.svgUrl)
.then(() => {
console.log('SVG reloaded successfully!');
})
.catch(() => {
console.error('Failed to reload SVG.');
});
}
}
MySvgComponent
:import { Component, Input } from '@angular/core';
@Component({
selector: 'app-my-svg',
template: `
`,
})
export class MySvgComponent {
@Input() svgUrl: string;
}
现在,你可以使用SvgComponent
来加载和重新加载预加载的SVG。调用loadSvg()
方法来加载SVG,调用reloadSvg()
方法来重新加载SVG。