问题
All tutorials with adding svg to a component in AngularCli that I found recommend to insert it in html template, something like this:
<div>
<svg viewBox="0 0 250 250">
<svg:g class="group">
<svg:polygon class="shield" points="125,30 125,30 125,30 31.9,63.2 46.1,186.3 125,230 125,230 125,230 203.9,186.3 218.1,63.2" />
<svg:path class="a" d="M125,52.1L66.8,182.6h0h21.7h0l11.7-29.2h49.4l11.7,29.2h0h21.7h0L125,52.1L125,52.1L125,52.1L125,52.1
L125,52.1z M142,135.4H108l17-40.9L142,135.4z"/>
</svg:g>
</svg>
</div>
But I wish to keep templates clear and instert only few tags in it with url to separated svg file, somwehow like this:
<svg class="star">
<use xlink:href="../../../assets/images/svg/star.svg"
x="0"
y="0" />
</svg>
Ho do I use separated svg files in components?
回答1:
Include your SVG files in src/assets folder and add the svg folder in your angular.json
file.
"assets": [ "src/assets/svg/*" ]
This way you can include the file in your components as you wish.
回答2:
one way to do this is to set id property for your svg file and put your svg files in your asset folder. then use that id in mat-icon like this:
<mat-icon matSuffix svgIcon="your-id"></mat-icon>
this is a better way to do it; in this way you don't have to deal with svg tags in your UI html code. also this supports google icons.
though this works if you're using angular material.
回答3:
If you have logo.svg
:
- Put it inside your
src/assets
folder - Include folder in the
angular.json
config:"assets": [ "src/assets" ]
- Refer to it from template:
<img src="assets/svg/logo.svg">
来源:https://stackoverflow.com/questions/53066823/how-do-i-import-svg-from-file-to-a-component-in-angular-5