Reputation: 681
I'm trying to insert an svg element (requested with http.get()) into an component 'icon'.
export class BgIcon {
private svgSrc_: string;
icon_: Icon;
@Input('svg-src')
set svgSrc(value: string) {
this.svgSrc_ = value;
this.icon_ = this.iconService.getIcon('cake.svg');
this.adapter_.setInnerHTML(this.elementRef_.nativeElement, this.icon_.svg);
}
get svgSrc(): string {
return this.svgSrc_;
}
constructor(private elementRef_: ElementRef,
private renderer_: Renderer,
public iconService: IconService,
private adapter_: BrowserDomAdapter) {
}
}
The IconService returns a cached object, with svg having the full svg-element as a string. I can make the svg appear, with the above method. But I don't know if this is correct angular2'ish.
Are there any better ways to accomplish such a task?
Upvotes: 2
Views: 1245
Reputation: 71911
I am not sure if this is a better, more angular2'ish way. But I use the @HostBinding()
for this. This results in something like this:
@Directive({
selector: 'bg-icon'
})
export class IconComponent {
@Input() public svgSrc : string;
@HostBinding('innerHtml') public svg : string = '';
constructor(public iconService: IconService) {}
ngOnInit() {
this.svg = this.iconService.getIcon(this.svgSrc).svg;
}
}
Upvotes: 4