Reputation: 363
I tried many attempts to bind SVG data path but no one seems to work. Here my code:
<div *ngFor="let icon of icons"">
<object type="image/svg+xml" [data]="icon.path"></object>
</div>
Ts:
public icons = [ {name: '...', path: '/svg/...svg', href: 'https://...'},..,];
I tried to use [data], data = "{{...}}", and so on. I am not getting any particular error, just I am not able to visualize any image. I am using object tag to have the possibility to change the "fill" property dynamically. I tried to directly write the path within the data property of the object tag and it works correctly. Any ideas on how to solve the problem?
Upvotes: 1
Views: 1776
Reputation: 9831
The problem is that Angular will block the URL due to security issues. You can tell Angular the URL is safe.
Create a new @Pipe
as described below and use it in the template
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({ name: 'safeUrl' })
export class SafeUrlPipe implements PipeTransform
{
public constructor(private _domSanitizer: DomSanitizer) {}
public transform(unsafeUrl: string): SafeResourceUrl {
return this._domSanitizer.bypassSecurityTrustResourceUrl(unsafeUrl);
}
}
HTML
<object type="image/svg+xml" [data]="getUrl() | safeUrl"></object>
Upvotes: 2
Reputation: 735
What about the attr.data
?
<div *ngFor="let icon of icons"">
<object type="image/svg+xml" [attr.data]="icon.path"></object>
</div>
as shown here.
EDIT:
Would be better to sanitize the path before.
<!-- COMPONENT -->
import { DomSanitizationService } from '@angular/platform-browser';
@Component({
...
})
export class SvgComponent {
private sanitizer;
constructor(sanitizer: DomSanitizationService ) {
this.sanitizer = sanitizer;
}
svgURL(url) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
}
<!-- TEMPLATE -->
<div *ngFor="let icon of icons"">
<object type="image/svg+xml" [attr.data]="svgURL(icon.path)"></object>
</div>
Upvotes: 4