angular4导入html文件

时间:2017-09-14 06:07:24

标签: javascript angular svg

我想在组件变量'a'或svgicon.component.html中保存test.svg 所以,我创建了svgicon.component.ts文件。 但没有工作。 我该怎么办?

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>

文件夹目录

enter image description here

2 个答案:

答案 0 :(得分:0)

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

或(取决于a的内容)

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

您可能需要应用清理程序来说服Angular添加a的内容是安全的。有关详细信息,请参阅In RC.1 some styles can't be added using binding syntax

答案 1 :(得分:0)

案例1

如果您的组件变量a包含svg url的路径

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'/>

<强>情况2

如果您的组件varibale a包含svg模板

  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>