Angular reusable component that displays SVG icons has width/height not set anywhere & positioned right under the icon, stackblitz inside

Viewed 663

Stackblitz link here.

So I'm using global icon-definitions loaded in app component once and then poiting to it throughout my app with this reusable icon.

For the most part it works well & nice but for some reason I noticed that the positioning of the SVG is outside the boundaries of the icon component and instead it shows up as some empty div at the bottom of the SVG, screenshot:

enter image description here

This is the relevant icon component code:

<svg
    version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    [style.width]="width ? width : size"
    [style.height]="height ? height : size"
    [style.margin]="margin ? margin : '0'"
    [style.padding]="padding ? padding : '0'"
>
    <use [style.fill]="color ? color : 'white'" [attr.xlink:href]="absUrl + '#' + name"></use>
</svg>

and the actual ts code:

import { Component, ChangeDetectionStrategy, Input } from "@angular/core";

@Component({
    selector: "icon",
    templateUrl: "./icon.component.html",
    styleUrls: ["./icon.component.scss"],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class IconComponent {
    @Input() name: string;
    @Input() size: string;
    @Input() color: string;
    @Input() width?: string;
    @Input() height?: string;
    @Input() margin?: string;
    @Input() padding?: string;
    get absUrl() {
        return window.location.href.split("#")[0];
    }
}

I've tried to set line-height and icon height to 0 with !important which does not work/affect anything at all.

However if I set the whole icon div to hidden, the SVG won't display either.

Not sure what else to try, thanks!

1 Answers

Svg is an inline element. inline elements leave white-space. If you set display:block on svg element or icon component it will be fixed.

Try this:

icon.component.scss

:host{
  display: block;
}

Forked Example

Detailed Explanation

Related