skip to Main Content

In angular, I am displaying an SVG:

<div [innerHTML]="svgImage" class="center">
</div>

The SVG contains polygons with a unique ID, for example:

<polyline id="tp_31" fill="#FFFAEC" points="698.814,494.607 719.188,459.31 698.813,424.014 658.064,424.015 637.69,459.313
        658.065,494.608 698.814,494.607     "/>

I am able to style each polygon individually in the SCSS file with an id selector:

#tp_31:hover {
  fill: blue;
}

However, I am not sure how to do this dynamically. The SVG image will be coming from a server and I would like to style it programatically. How can I best achieve this? I’ve tried using [ngStyle] but I am not sure how to use it with an id selector. Thanks!

2

Answers


  1. To dynamically style elements in an SVG that’s being injected with [innerHTML]="svgImage", you can utilize Angular’s Renderer2 to manipulate the SVG content after it has been rendered.

    Create a ViewChild to reference the container:

    import { ElementRef, ViewChild, Renderer2 } from '@angular/core';
    
    @ViewChild('svgContainer') svgContainer: ElementRef;
        
    constructor(private renderer: Renderer2) {}
    

    Inject the SVG content with [innerHTML]:

    <div #svgContainer [innerHTML]="svgImage" class="center"></div>
    

    Use Renderer2 to set styles:

    ngAfterViewInit() {
      const container = this.svgContainer.nativeElement;
    
      const polygon = container.querySelector('#tp_31');
    
      this.renderer.setStyle(polygon, 'fill', 'blue');
      this.renderer.setStyle(polygon, 'stroke', 'red');
    }
    
    Login or Signup to reply.
  2. you can interact with DOM directly

    import { ElementRef, AfterViewInit } from '@angular/core';
    
    constructor(private el: ElementRef) { }
    
    ngAfterViewInit() {
        const svgElement = this.el.nativeElement.querySelector('#tp_31');
        if (svgElement) {
            svgElement.addEventListener('mouseover', () => {
                svgElement.setAttribute('fill', 'blue');
            });
            svgElement.addEventListener('mouseout', () => {
                svgElement.setAttribute('fill', '#FFFAEC');
            });
        }
    }
    

    your second option is using render

    import { Renderer2, ElementRef } from '@angular/core';
    
    constructor(private el: ElementRef, private renderer: Renderer2) { }
    
    ngAfterViewInit() {
        const svgElement = this.el.nativeElement.querySelector('#tp_31');
        if (svgElement) {
            this.renderer.listen(svgElement, 'mouseover', () => {
                this.renderer.setStyle(svgElement, 'fill', 'blue');
            });
            this.renderer.listen(svgElement, 'mouseout', () => {
                this.renderer.setStyle(svgElement, 'fill', '#FFFAEC');
            });
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search