The angular-svg-icon is an Angular 12 service and component that provides ameans to inline SVG files to allow for them to be easily styled by CSS and code.
The service provides an icon registery that loads and caches a SVG indexed byits url. The component is responsible for displaying the SVG. After getting thesvg from the registry it clones the SVGElement
and the SVG to the component'sinner HTML.
This demo shows this module in action.
$ npm i angular-svg-icon --save
Note on earlier versions of Angular:
See the module's accompanying README.md for instructions.
The angular-svg-icon should work as-is with webpack/angular-cli. Just import theAngularSvgIconModule
and the HttpClientModule
.
import { HttpClientModule } from '@angular/common/http';
import { AngularSvgIconModule } from 'angular-svg-icon';
@NgModule({
imports: [ HttpClientModule, AngularSvgIconModule.forRoot() ],
...
})
export class AppModule {}
BREAKING CHANGE: as of angular-svg-icon@9.0.0, an explicit call to forRoot()
must be made on the module's import.
Recommened usage pattern is to import AngularSvgIconModule.forRoot()
in only the root AppModule of your application.In child modules, import only AngularSvgIconModule
.
Recommended usage pattern is to import AngularSvgIconModule.forRoot()
in the root AppModule of your application.This will allow for one SvgIconRegistryService
to be shared across all modules.If, for some reason, a lazily loaded module needs encapuslation of the service, then it is possible to load theAngularSvgIconModule.forRoot()
in each lazy loaded module, but such usage precludes loading the package in the rootAppModule.
Basic usage is:
<svg-icon src="images/eye.svg" [svgStyle]="{ 'width.px':90 }"></svg-icon>
Note that without a height or width set, the SVG may not display!
If svg was previously loaded via registry with name it can be used like this:
<svg-icon name="eye" [svgStyle]="{ 'width.px':90 }"></svg-icon>
More complex styling can be applied to the svg, for example:
<svg-icon src="images/eye.svg" [stretch]="true"
[svgStyle]="{'width.px':170,'fill':'rgb(150,50,255)','padding.px':1,'margin.px':3}">
</svg-icon>
The following attributes can be set on svg-icon:
preserveAspectRatio="none"
on the SVG. This is useful for setting both the height and width styles to strech or distort the svg.svg-icon
).class
attribute on the svg-icon
and adds it to the SVG.svg-icon
).viewBox="auto"
, then svg-icon
will attempt to convert the SVG's width and height attributes to a viewBox="0 0 w h"
. Both explicitly setting the viewBox or auto
setting the viewBox will remove the SVG's width and height attributes.aria-label
. If the SVG does not have a pre-existing aria-label
and the svgAriaLabel
is not set, then the SVG will be loaded with aria-hidden=true
. If the SVG has an aria-label
, then the SVG's default will be used. To remove the SVG's aria-label
, assign an empty string ''
to svgAriaLabel
. Doing so will remove any existing aria-label
and set aria-hidden=true
on the SVG.Deprecated attribute:
Programatic interaction with the registry is also possible.Include the private iconReg: SvgIconRegistryService
in the constructor:
constructor(private iconReg:SvgIconRegistryService) { }
The registry has three public functions: loadSvg(string)
, addSvg(string, string)
, and unloadSvg(string)
.
To preload a SVG file from a URL into the registry:
{
...
this.iconReg.loadSvg('foo.svg').subscribe();
}
To preload a SVG file from a URL into the registry with predefined name:
{
...
this.iconReg.loadSvg('foo.svg', 'foo').subscribe();
}
To add a SVG from a string:
{
...
this.iconReg.addSvg('box',
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M1 1 L1 9 L9 9 L9 1 Z"/></svg>'
);
}
To unload a SVG from the registry.
{
...
this.iconReg.unloadSvg('foo.svg');
}
When rendering on server-side, the SVGs must be loaded via the file system.This can be achieved by providing an SvgLoader
to the server module:
export function svgLoaderFactory(http: HttpClient, transferState: TransferState) {
return new SvgServerLoader('browser/assets/icons', transferState);
}
@NgModule({
imports: [
AngularSvgIconModule.forRoot({
loader: {
provide: SvgLoader,
useFactory: svgLoaderFactory,
deps: [ HttpClient, TransferState ],
}
}),
AppModule,
ServerModule,
ServerTransferStateModule,
ModuleMapLoaderModule,
],
bootstrap: [ AppComponent ],
})
export class AppServerModule {
}
The loader itself is up to you to implement because it depends on where youricons are stored locally. An implementation that additionally saves the iconsin the transfer state of your app in order to avoid double requests could looklike that:
const fs = require('fs');
const join = require('path').join;
const parseUrl = require('url').parse;
const baseName = require('path').basename;
export class SvgServerLoader implements SvgLoader {
constructor(private iconPath: string,
private transferState: TransferState) {
}
getSvg(url: string): Observable<string> {
const parsedUrl:URL = parseUrl(url);
const fileNameWithHash = baseName(parsedUrl.pathname);
// Remove content hashing
const fileName = fileNameWithHash.replace(/^(.*)(\.[0-9a-f]{16,})(\.svg)$/i, '$1$3');
const filePath = join(this.iconPath, fileName);
return Observable.create(observer => {
const svgData = fs.readFileSync(filePath, 'utf8');
// Here we save the translations in the transfer-state
const key: StateKey<number> = makeStateKey<number>('transfer-svg:' + url);
this.transferState.set(key, svgData);
observer.next(svgData);
observer.complete();
});
}
}
Note that this is executed in a local Node.js context, so the Node.js API isavailable.
A loader for the client module that firstly checks the transfer state couldlook like that:
export class SvgBrowserLoader implements SvgLoader {
constructor(private transferState: TransferState,
private http: HttpClient) {
}
getSvg(url: string): Observable<string> {
const key: StateKey<number> = makeStateKey<number>('transfer-svg:' + url);
const data = this.transferState.get(key, null);
// First we are looking for the translations in transfer-state, if none found, http load as fallback
if (data) {
return Observable.create(observer => {
observer.next(data);
observer.complete();
});
} else {
return new SvgHttpLoader(this.http).getSvg(url);
}
}
}
This is executed on browser side. Note that the fallback when no data isavailable uses SvgHttpLoader
, which is also the default loader if you don'tprovide one.
angular-svg-icon
An Angular Universal example project is also available. The basic steps to get it work is:
package.json
file to prevent compilation issues:"browser": {
"fs": false,
"path": false,
"os": false
}
ServerTransferStateModule
to app.server.module
BrowserTransferStateModule
to app.module
PLATFORM_ID
and load the correct class appropriately (this is already added in the example).The SVG should be modified to remove the height and width attributes from the fileper Sara Soueidan's advice in "Making SVGs Responsive WithCSS" ifsize is to be modified through CSS. Removing the height and width has two immedateimpacts: (1) CSS can be used to size the SVG, and (2) CSS will be required tosize the SVG.
The svg-icon is an Angular component that allows for the continuation of theAngularJS method for easily inlining SVGs explained by BenMarkowitz and others. Includingthe SVG source inline allows for the graphic to be easily styled by CSS.
The technique made use of ng-include to inline the svg source into the document.Angular 2, however, dropped the support of ng-include, so this was my work-aroundmethod.
Note: The iconcomponent fromangular/material2 used to have a directmeans to load svg similar to this, but this functionality was removed because ofsecurity concerns.
MIT
基于angular7写的一个指令,在ionic3.x项目在用。因为加载图片超时等原因导致图片显示不出来,需要替换成默认或者指定图片 1.err-src.ts import { Directive,Input } from '@angular/core'; @ Directive({ selector: '[err-src]', // Attribute selector host: {
angular.json中加入: "assets": [ "src/favicon.ico", "src/assets", { "glob": "**/*", "input": "./node_modules/@ant-design/icons-ang
阿里icon 直接放入assets文件夹后 html引入即可 <div> <img src="yourIcon.svg"> </div> 注意: 根位置是index.html文件所在的位置 动态更改svg 可以使用ngStyle指令 <circle [ngStyle]="{stroke:stroke, fill: fill}" id="XMLID_1_" class="
引入第三方类库 进入到auction文件,在cmd中输入cnpm install jquery --save,save是将jquery的信息保存的在package.json文件中。或者在WebStorm中打开一个Terminal输入这个命令。 之后在输入cnpm install bootstrap --save 都装好后,可以看看package.json文件会多两句话 "bootstrap": "
前提: https://v10.material.angular.io/components/icon/overview TS import {MatIconRegistry} from '@angular/material/icon'; import {DomSanitizer} from '@angular/platform-browser'; constructor( private
首先分享一个图标库,由阿里巴巴分享:iconfont.cn。 如果我要使用iconfont.cn上的svg,那么首先下载图标到assets目录中,然后使用MdIconRegistry和DomSanitizer完成。 我们可以在module.ts中统一引入图标,那么在module下的所有组件就可以自由使用,一次性加载,节约资源。以后如果需要使用svg,只需要在app/utils/svg.util.t
前言 在angular里面使用阿里图标的svg显示图标,图标是通过接口返回,需要xlink:href的数据是动态化的,直接使用{{}}后发现报错,错误写法如下: <svg class="icon" aria-hidden="true"><use xlink:href="{{icon}}"></use></svg> <svg class="icon" aria-hidden="true"><use
Angular SVG round progressbar Angular module that uses SVG to create a circular progressbar Demo Click here for the Angular 1.x version Install First you have to install the module through npm: npm in
我在Angular应用程序中使用服务工作者。我的资产文件夹中的所有文件都被缓存,正如我的文件中声明的那样。 我有。svg和。“我的资源”文件夹中的png文件。当我为生产构建应用程序并第一次访问我的站点时,一切正常,但一旦我重新加载页面,我的控制台就会出现以下错误。 未捕获(promise中)错误:哈希不匹配(cacheBustedFetchFromNetwork) 此问题仅发生在浏览器试图获取.
此外,我尝试以以下方式使用对象标记: 但是,同样,如果我用CSS指令或将类应用到对象标记,则不会发生任何变化。有什么想法可以实现我想要的吗?
支付网关图标 支付网关图标对于电子商务应用服务提供商是有用的。 下面提供了一些授权电子商务,在线零售商,砖块和点击或传统砖公司图标的信用卡付款。
A lightweight library that makes it easier to use SVG icons in your Angular Application The svg-icon library enables using the <svg-icon> tag to directly display SVG icons in the DOM.This approach off
描述 (Description) svg-gradient是一种颜色到另一种颜色的过渡。 它可以为同一个元素添加许多颜色。 它至少包含三个参数 - 第一个参数标识渐变类型和方向。 其他参数列出其位置和颜色。 在第一个和最后一个位置指定的颜色是可选的。 可以设置方向 - 从中心到底部,右边,右下角,右上角,椭圆或椭圆。 参数 - 颜色在列表中停止 - list - 列出所有颜色及其位置。 esc