Angular2 SVG xlink:href

50

我有一个用于渲染SVG图标的组件:

import {Component, Directive} from 'angular2/core';
import {COMMON_DIRECTIVES} from 'angular2/common';

@Component({
  selector: '[icon]',
  directives: [COMMON_DIRECTIVES],
  template: `<svg role="img" class="o-icon o-icon--large">
                <use [xlink:href]="iconHref"></use>
              </svg>{{ innerText }}`
})
export class Icon {
  iconHref: string = 'icons/icons.svg#menu-dashboard';
  innerText: string = 'Dashboard';
}

这会触发错误:

EXCEPTION: Template parse errors:
  Can't bind to 'xlink:href' since it isn't a known native property ("<svg role="img" class="o-icon o-icon--large">
<use [ERROR ->][xlink:href]=iconHref></use>
  </svg>{{ innerText }}"): SvgIcon@1:21

我该如何设置动态的 xlink:href
3个回答

93

SVG元素没有属性,因此大部分时间都需要使用属性绑定(另请参见HTML中的属性和特性)。

要进行属性绑定,您需要

<use [attr.xlink:href]="iconHref">
或者
<use attr.xlink:href="{{iconHref}}">

更新

过滤可能会导致问题。

另请参见

更新 在 RC.6 中,DomSanitizationService 将被重命名为DomSanitizer

更新 应该已经修复了。

但是,仍然有一个未解决的问题需要支持命名空间属性 https://github.com/angular/angular/pull/6363/files

作为解决方法,请添加一个额外的

xlink:href=""

Angular可以更新属性,但添加属性存在问题。

如果xlink:href实际上是一个属性,那么在PR添加后,您的语法应该可以正常工作。


2
谢谢!现在iconHref已经呈现在DOM中了。但是图标仍然没有显示,就像SVG没有选择更改一样。看起来这需要PR才能正常工作。 - tomaszbak
2
请注意,这也适用于图像标签。<image attr.xlink:href="http://somewhere.com/{{restOfUrl}}" /> - Zachary Scott

3

我仍然遇到了由Gunter描述的attr.xlink:href问题,所以我创建了一个指令,它类似于SVG 4 Everybody,但是特别为angular2设计。

用法

<div [useLoader]="'icons/icons.svg#menu-dashboard'"></div>

说明

这个指令会:

  1. 通过http加载icons/icons.svg
  2. 解析响应并提取#menu-dashboard路径信息
  3. 将已解析的svg图标添加到html中

代码

import { Directive, Input, ElementRef, OnChanges } from '@angular/core';
import { Http } from '@angular/http';

// Extract necessary symbol information
// Return text of specified svg
const extractSymbol = (svg, name) => {
    return svg.split('<symbol')
    .filter((def: string) => def.includes(name))
    .map((def) => def.split('</symbol>')[0])
    .map((def) => '<svg ' + def + '</svg>')
}

@Directive({
    selector: '[useLoader]'
})
export class UseLoaderDirective implements OnChanges {

    @Input() useLoader: string;

    constructor (
        private element: ElementRef,
        private http: Http
    ) {}

    ngOnChanges (values) {
        if (
            values.useLoader.currentValue &&
            values.useLoader.currentValue.includes('#')
        ) {
            // The resource url of the svg
            const src  = values.useLoader.currentValue.split('#')[0];
            // The id of the symbol definition
            const name = values.useLoader.currentValue.split('#')[1];

            // Load the src
            // Extract interested svg
            // Add svg to the element
            this.http.get(src)
            .map(res => res.text())
            .map(svg => extractSymbol(svg, name))
            .toPromise()
            .then(svg => this.element.nativeElement.innerHTML = svg)
            .catch(err => console.log(err))
        }
    }
}

0

我认为可以使用 Angular 的管道功能来解决这个问题。

<use attr.xlink:href={{weatherData.currently.icon|iconpipe}}></use>

说明 这个管道将会:

  1. 将解析后的响应值传递给管道
  2. 返回完整的SVG路径
  3. attr.xlink:href= 将获取预期的路径,SVG 将在 HTML 页面中呈现

这是管道 TypeScript 代码

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({
    name: 'iconpipe'
})
export class IconPipe implements PipeTransform {
    constructor() { }

    transform(value: any) {
        let properIconName = undefined;

        switch (value) {
            case 'clear-day':
                properIconName = '/assets/images/weather-SVG-sprite.svg#sun';
                break;
            case 'clear-night':
                properIconName = '/assets/images/weather-SVG-sprite.svg#night-1';
                break;
            case 'partly-cloudy-day':
                properIconName = '/assets/images/weather-SVG-sprite.svg#cloudy';
                break;

            case 'partly-cloudy-night':
                properIconName = '/assets/images/weather-SVG-sprite.svg#night';
                break;

            case 'cloudy':
                properIconName = '/assets/images/weather-SVG-sprite.svg#cloud';
                break;

            case 'rain':
                properIconName = '/assets/images/weather-SVG-sprite.svg#rain';
                break;

            case 'sleet':
                properIconName = '/assets/images/weather-SVG-sprite.svg#snowflake';
                break;
            case 'snow':
                properIconName = '/assets/images/weather-SVG-sprite.svg#snowing';
                break;

            case 'wind':
                properIconName = '/assets/images/weather-SVG-sprite.svg#storm';
                break;
            case 'fog':
                properIconName = '/assets/images/weather-SVG-sprite.svg#sun';
                break;
            case 'humid':
                properIconName = '/assets/images/weather-SVG-sprite.svg#sun';
                break;
            default:
                properIconName = '/assets/images/weather-SVG-sprite.svg#summer';
        }
        return properIconName;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接