Reputation: 93
I've been trying to add some assets into an Angular 8 library.
The library was created with ng generate library and my goal is to include some icons in SVG format to be used inside the HTML component's templates.
So far I've tried to add the library's assets folder to the parent application angular.json file, but to no avail. While developing my assets, in a folder at the library source root, is unreachable. Copying the folder to the dist one once the library is built haven't work either.
What's the proper way of including assets folder into the library, just like it is done for an app? I think this is a fairly frecuent use case, since components rely on icons usually. Also a method to embed the SVG or PNG into SCSS files will be enough to solve this use-case.
Upvotes: 7
Views: 4143
Reputation: 564
I've fixed that problem adding the SVG icons to app.component.ts using DomSanitizer and MatIconRegistry libraries.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { MatIconRegistry } from '@angular/material';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(
private matIconRegistry: MatIconRegistry,
private domSanitizer: DomSanitizer
) {
this.matIconRegistry.addSvgIcon(
`icon-1`,
this.domSanitizer.bypassSecurityTrustResourceUrl("assets/images/icon-1.svg")
);
this.matIconRegistry.addSvgIcon(
`icon-2`,
this.domSanitizer.bypassSecurityTrustResourceUrl("assets/images/icon-2.svg")
);
this.matIconRegistry.addSvgIcon(
`icon-3`,
this.domSanitizer.bypassSecurityTrustResourceUrl("assets/images/icon-3.svg")
);
.
.
.
}
ngOnInit() {
}
}
Then in the html of your component add the image as follow:
myComponent.component.html
<ul>
<li>
<a href="#">
<mat-icon svgIcon="icon-1"></mat-icon>
<span>Icon 1</span>
</a>
</li>
<li>
<a href="#">
<mat-icon svgIcon="icon-2"></mat-icon>
<span>Icon 2</span>
</a>
</li>
<li>
<a href="#">
<mat-icon svgIcon="icon-3"></mat-icon>
<span>Icon 3</span>
</a>
</li>
</ul>
Upvotes: 1