Tengo un componente para representar el icono 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'; }Esto desencadena un error:
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 ¿Cómo configuro xlink:href dinámico?
Los elementos SVG no tienen propiedades, por lo tanto, la vinculación de atributos se requiere la mayor parte del tiempo (consulte también Propiedades y atributos en HTML ).
Para el enlace de atributos que necesita
<use [attr.xlink:href]="iconHref">o
<use attr.xlink:href="{{iconHref}}">Actualizar
La desinfección puede causar problemas.
Ver también
Actualizar DomSanitizationService se cambiará el nombre a DomSanitizer en RC.6
Actualizar esto debería arreglarse
pero hay un problema abierto para admitir esto para los atributos de espacio de nombres https://github.com/angular/angular/pull/6363/files
Como solución, agregue un adicional
xlink:href=""Angular puede actualizar el atributo pero tiene problemas para agregar.
Si xlink:href es en realidad una propiedad, entonces su sintaxis también debería funcionar después de agregar el PR.
Todavía tenía problemas con attr.xlink:href descrito por Gunter , así que creé una directiva que es similar a SVG 4 Everybody pero es específica para angular2.
<div [useLoader]="'icons/icons.svg#menu-dashboard'"></div>
Esta directiva se
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)) } } }Creo que se puede resolver usando la función de tubería angular.
<use attr.xlink:href={{weatherData.currently.icon|iconpipe}}></use>Explicación Esta tubería
attr.xlink:href= obtendrá la ruta esperada y svg se representará en la página htmlaquí está el código mecanografiado de tubería
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; } }