简体   繁体   中英

angular4 import html file

I want to save test.svg in component variable 'a' or svgicon.component.html.
So, I create svgicon.component.ts file. but not working. what should I do?

svgicon.component.ts

 import { Component, OnInit } from '@angular/core'; import { svgs } from './svg/test.svg'; @Component({ selector: 'app-svgicon', templateUrl: './svgicon.component.html', styleUrls: ['./svgicon.component.css'] }) export class SvgiconComponent implements OnInit { public a: string = svgs; constructor() { } ngOnInit() { } } 

test.svg

<svg version="1.1" width="10" height="14" viewBox="0 0 10 14"> <path fill="#D4D4D4" d="M5,0.024c-2.761,0-5,2.269-5,5.069c0,1.139,0.37,2.19,0.996,3.036l-0.02,0.039l2.664,3.856l1.349,1.953 l1.339-1.953l2.62-3.82C9.607,7.345,10,6.265,10,5.093C10,2.293,7.761,0.024,5,0.024z M5,7.024c-1.105,0-2-0.895-2-2s0.895-2,2-2 s2,0.895,2,2S6.105,7.024,5,7.024z" /> </svg>

folder directory

enter image description here

<div [innerHTML]="a"></div>

or (depending on the content of a )

<svg [innerHTML]="a"></svg>

You might need to apply the sanitizer to convince Angular that it's safe to add the content of a . For more details see In RC.1 some styles can't be added using binding syntax

Case 1

If your component variable a contain path of svg url like

export class SvgiconComponent implements OnInit {
  public a: string = 'test.svg';

}

Then use this path inside your image src to render svg image:

<img [src]='a'/>

Case2

If your component varibale a contain svg template

  export class SvgiconComponent implements OnInit {
      public a: string = `<svg version="1.1" width="10" height="14" viewBox="0 0 10 14">
      <path fill="#D4D4D4" d="M5,0.024c-2.761,0-5,2.269-5,5.069c0,1.139,0.37,2.19,0.996,3.036l-0.02,0.039l2.664,3.856l1.349,1.953 l1.339-1.953l2.62-3.82C9.607,7.345,10,6.265,10,5.093C10,2.293,7.761,0.024,5,0.024z M5,7.024c-1.105,0-2-0.895-2-2s0.895-2,2-2 s2,0.895,2,2S6.105,7.024,5,7.024z" />
    </svg>`;

      constructor() { }

      ngOnInit() {
      }

    }

In this scenario you need to add this inside your template `(svgicon.component.html)`:

<div [innerHTML]='a'></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM