1

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?

2 Answers 2

4

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, already tried but without any success. I am getting the following error: Error: unsafe value used in a resource URL context
Solved by using that solutions link and attr.data.
Perfect, few moments ago i've updated my answer with more or less the same solution ;)
2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.