Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Octicon with angular 2

I was creating an app using angular 2, bootstrap 4 and I found out that glyphicons were dropped, so I have decided to use Octicon as suggested,

I did npm install --save octicons

After that I didn't under stand a thing. I thought i have to include octicons.css only but that didn't work.

It only contains

.octicon {
  display: inline-block;
  vertical-align: text-top;
  fill: currentColor;
}

What is a simple step bu step way to use Octicon?

like image 645
Dinkar Thakur Avatar asked Dec 29 '16 11:12

Dinkar Thakur


1 Answers

This gets you actual SVG tags easily reusable in your Angular app. Credit goes to robisim74 on GitHub, but posting here since this was a high Google result when I was trying to figure it out.

  1. npm install --save octicons

  2. In your .angular-cli.json file under styles:

    "../node_modules/octicons/build/build.css",

  3. Build a directive that you pass the icon's name to (searchable at https://octicons.github.com/). This is one way to do it, but look through the logic and you can imagine doing it other ways if it made sense to for your app. You'd probably make this directive within your SharedModule and import SharedModule into whatever feature modules you want to use it.

import { Directive, Input, OnInit, ElementRef, Renderer2 } from '@angular/core';

import * as octicons from 'octicons';

@Directive({
    selector: '[octicon]'
})
export class OcticonDirective implements OnInit {

    @Input() octicon: string;
    @Input() color: string;
    @Input() width: number;

    constructor(private elementRef: ElementRef, private renderer: Renderer2) { }

    ngOnInit(): void {
        const el: HTMLElement = this.elementRef.nativeElement;
        el.innerHTML = octicons[this.octicon].toSVG();

        const icon: Node = el.firstChild;
        if (this.color) {
            this.renderer.setStyle(icon, 'fill', this.color);
        }
        if (this.width) {
            this.renderer.setStyle(icon, 'width', this.width);
            this.renderer.setStyle(icon, 'height', '100%');
        }
    }

}
  1. Then in your template, some example usages:

    <span octicon="gear"></span>

    <span octicon="gear" color="red" width="32"></span>

like image 158
jmq Avatar answered Sep 21 '22 05:09

jmq