Подтвердить что ты не робот

Angular2 SVG xlink: href

У меня есть компонент для отображения значка 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 }}"): [email protected]:21

Как установить динамический xlink:href?

4b9b3361

Ответ 1

Элементы SVG не имеют свойств, поэтому привязка привязки требуется большую часть времени (см. также Свойства и атрибуты в HTML).

Для привязки атрибута вам нужно

<use [attr.xlink:href]="iconHref">

или

<use attr.xlink:href="{{iconHref}}">

Обновление

Санитария может вызвать проблемы.

См. также

Обновление DomSanitizationService будет переименовано в DomSanitizer в RC.6

Обновить, это должно быть исправлено

но есть открытая проблема для поддержки этого для атрибутов с расширением имен https://github.com/angular/angular/pull/6363/files

В процессе работы добавьте еще

xlink:href=""

Angular может обновлять атрибут, но имеет проблемы с добавлением.

Если xlink:href на самом деле является свойством, ваш синтаксис должен работать после добавления PR.

Ответ 2

У меня все еще были проблемы с attr.xlink: href, описанным Gunter, поэтому я создал директиву, похожую на SVG 4 Все, но специфично для angular2.

Использование

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

Описание

Эта директива будет

  • Загрузить значки /icons.svg через http
  • Разберите ответ и извлеките информацию о пути для # menu-dashboard
  • Добавьте синтаксический символ 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))
        }
    }
}