All Projects → czeckd → Angular Svg Icon

czeckd / Angular Svg Icon

Licence: mit
Angular component for inlining SVGs allowing them to be easily styled with CSS.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Angular Svg Icon

Vivid
a JavaScript library which is built to easily customize and use the SVG Icons with a blaze.
Stars: ✭ 1,797 (+1090.07%)
Mutual labels:  svg, svg-icons
Icons
The premium icon font for @uiwjs Component Library. https://uiwjs.github.io/icons
Stars: ✭ 99 (-34.44%)
Mutual labels:  svg, svg-icons
Svg Native Viewer
SVG Native viewer is a library that parses and renders SVG Native documents
Stars: ✭ 85 (-43.71%)
Mutual labels:  svg, svg-icons
Svgeez
A Ruby gem for automatically generating an SVG sprite from a folder of SVG icons.
Stars: ✭ 69 (-54.3%)
Mutual labels:  svg, svg-icons
Coreui Icons
CoreUI Free Icons - Premium designed free icon set with marks in SVG, Webfont and raster formats
Stars: ✭ 1,813 (+1100.66%)
Mutual labels:  svg, svg-icons
Svgsprit.es
Public endpoint to generate SVG Sprites
Stars: ✭ 73 (-51.66%)
Mutual labels:  svg, svg-icons
Phosphor React
A flexible icon family for React
Stars: ✭ 97 (-35.76%)
Mutual labels:  svg, svg-icons
React Icomoon
It allows you to simply view the icons in the selection.json file provided by Icomoon.
Stars: ✭ 48 (-68.21%)
Mutual labels:  svg, svg-icons
Simple Icons
SVG icons for popular brands
Stars: ✭ 12,090 (+7906.62%)
Mutual labels:  svg, svg-icons
Tabler Icons
A set of over 1400 free MIT-licensed high-quality SVG icons for you to use in your web projects.
Stars: ✭ 10,858 (+7090.73%)
Mutual labels:  svg, svg-icons
Phosphor Icons
A flexible icon family for the web
Stars: ✭ 56 (-62.91%)
Mutual labels:  svg, svg-icons
Svg To Ts
Build performant SVG icon libraries by converting raw SVG files to TypeScript that is optimized for modern tree shaking mechanisms.
Stars: ✭ 131 (-13.25%)
Mutual labels:  svg, svg-icons
Boxicons
High Quality web friendly icons
Stars: ✭ 1,104 (+631.13%)
Mutual labels:  svg, svg-icons
Svg Autocrop
🚗🌽🔳An NPM module to autocrop and slim down SVGs
Stars: ✭ 80 (-47.02%)
Mutual labels:  svg, svg-icons
Vmware Stencils
Official VMware Stencils
Stars: ✭ 57 (-62.25%)
Mutual labels:  svg, svg-icons
React Cassette Player
Simple ReactJS HTML5 audio player component built with SVG icons from The Noun Project.
Stars: ✭ 93 (-38.41%)
Mutual labels:  svg, svg-icons
Vue Unicons
1000+ Pixel-perfect svg icons for your next project as Vue components
Stars: ✭ 828 (+448.34%)
Mutual labels:  svg, svg-icons
Mono Icons
Stars: ✭ 899 (+495.36%)
Mutual labels:  svg, svg-icons
Svg Icon
👻 A lightweight library that makes it easier to use SVG icons in your Angular Application
Stars: ✭ 112 (-25.83%)
Mutual labels:  svg, svg-icons
Svgiconimagelist
Three engines to render SVG (GDI+, Direct2D or Cairo) and four components to simplify use of SVG images (resize, fixedcolor, grayscale...): TSVGIconImage, TSVGIconImageCollection, TSVGIconVirtualImageList and TSVGIconImageList (for VCL and FMX).
Stars: ✭ 127 (-15.89%)
Mutual labels:  svg, svg-icons

npm version

Angular SVG Icon

The angular-svg-icon is an Angular 11 service and component that provides a means 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 by its url. The component is responsible for displaying the SVG. After getting the svg from the registry it clones the SVGElement and the SVG to the component's inner HTML.

This demo shows this module in action.

How to use?

$ npm i angular-svg-icon --save

Note on earlier versions of Angular:

See the module's accompanying README.md for instructions.

Integration

The angular-svg-icon should work as-is with webpack/angular-cli. Just import the AngularSvgIconModule 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 [email protected], an explicit call to forRoot() must be made on the module's import.

Child modules

Recommened usage pattern is to import AngularSvgIconModule.forRoot() in only the root AppModule of your application. In child modules, import only AngularSvgIconModule.

Use with Lazy Loading Feature Modules

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 the AngularSvgIconModule.forRoot() in each lazy loaded module, but such usage precludes loading the package in the root AppModule.

Usage

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:

  • src - The path to SVG.
  • name - An optional name of SVG, under which it was loaded via SvgIconRegistryService.
  • [svgStyle] - Optional styles to be applied to the SVG, this is based on the familiar [ngStyle].
  • [stretch] - An optional boolean (default is false) that when true, sets preserveAspectRatio="none" on the SVG. This is useful for setting both the height and width styles to strech or distort the svg.
  • [class] - An optional string of the class or classes to apply to the SVG (duplicates what is set on the svg-icon).
  • [applyClass] - An optional boolean (default is false) that copies the class attribute on the svg-icon and adds it to the SVG.
  • [svgClass] - An optional string of the class or classes to apply to the SVG (independent of what is set for the class on the svg-icon).
  • [viewBox] - An optional string to set the viewBox on the SVG. If the 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.
  • [svgAriaLabel] - An optional string to set the SVG's 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:

  • [applyCss] - Renamed as [applyClass] (as of v9.2.0).

Using the Svg-Icon Registry

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');
}

Usage with Angular Universal

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 your icons are stored locally. An implementation that additionally saves the icons in the transfer state of your app in order to avoid double requests could look like 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 is available.

A loader for the client module that firstly checks the transfer state could look 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 is available uses SvgHttpLoader, which is also the default loader if you don't provide one.

SVG Preparation

The SVG should be modified to remove the height and width attributes from the file per Sara Soueidan's advice in "Making SVGs Responsive With CSS" if size is to be modified through CSS. Removing the height and width has two immedate impacts: (1) CSS can be used to size the SVG, and (2) CSS will be required to size the SVG.

Background

The svg-icon is an Angular component that allows for the continuation of the AngularJS method for easily inlining SVGs explained by Ben Markowitz and others. Including the 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-around method.

Note: The icon component from angular/material2 used to have a direct means to load svg similar to this, but this functionality was removed because of security concerns.

License

MIT

Author

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].