首页 > 解决方案 > 显示 SVG 图标的 Angular 可重用组件的宽度/高度未在任何地方设置并位于图标正下方,stackblitz 内部

问题描述

Stackblitz 链接在这里。

所以我使用了一次加载到应用程序组件中的全局图标定义,然后使用这个可重用的图标在我的整个应用程序中指向它。

在大多数情况下,它运行良好且很好,但由于某种原因,我注意到 SVG 的位置超出了图标组件的边界,而是在 SVG 底部显示为一些空 div,截图:

在此处输入图像描述

这是相关的图标组件代码:

<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>

和实际的 ts 代码:

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];
    }
}

我尝试使用 !important 将 line-height 和 icon height 设置为 0,这根本不起作用/影响任何东西。

但是,如果我将整个图标 div 设置为隐藏,则 SVG 也不会显示。

不知道还有什么可以尝试的,谢谢!

标签: cssangularsvg

解决方案


Svg 是一个内联元素。内联元素留下空白。如果您在 svg 元素或图标组件上设置 display:block ,它将被修复。

尝试这个:

图标.component.scss

:host{
  display: block;
}

分叉示例

详细说明


推荐阅读