How to inject SVG icon sprites in Angular component HTML DOM?

前端 未结 4 1786
Happy的楠姐
Happy的楠姐 2021-02-15 22:12

I am building an Angular application (Angular 4/5/6) and would like to use SVG sprites in my component template.

Question: Assuming I already have my S

4条回答
  •  你的背包
    2021-02-15 22:45

    I was in your same boat today with designers pushing back about the svg font. I also did not want to move the icon def out of the node_modules because it would change over time. I came up with a solution.

    You need to first create an angular icon component, then do something like this:

    import { Component, OnInit, Input } from '@angular/core';
    declare const require;
    @Component({
      selector: 'my-icon',
      templateUrl: './my-icon.component.html',
      styleUrls: ['./my-icon.component.scss']
    })
    export class IconComponent implements OnInit {
    
      constructor() { }
    
      @Input() icon: string = "";
      @Input() x: string = "0";
      @Input() y: string = "0";
      @Input() fillColor: string = "black";
      @Input() strokeColor: string = "black";
      @Input() height: string = "";
      @Input() width: string = "";
      private baseUrl: string = require("../../../../../node_modules/path/to/defs.svg") + "#beginning-of-iconset-";
    
      svgUrl: string = "";
    
      ngOnInit() {
      }
    
      ngAfterViewInit() {
        setTimeout(()=>{
          this.svgUrl = this.baseUrl + this.icon;
        },0);
    
      }
    
    }
    

    And then, in the html:

    
      
    
    

    I'm still working on scaling the solution as the width and height attributes don't work as expected. You can also expand on the inputs as I know I will.

    Hope that helps.

提交回复
热议问题