How to include assets like icons in an Angular8 library?
我一直在尝试将一些资产添加到Angular 8库中。
该库是使用ng generate库创建的,我的目标是包括一些SVG格式的图标,以便在HTML组件模板中使用。
到目前为止,我尝试将库的资产文件夹添加到父应用程序angular.json文件中,但无济于事。开发资源时,无法访问库源根目录下的文件夹中。建立库后,将文件夹复制到dist也不起作用。
将资源文件夹包含到库中的正确方法是什么,就像对应用程序所做的那样?我认为这是一个相当流行的用例,因为组件通常依赖于图标。将SVG或PNG嵌入到SCSS文件中的方法也足以解决此用例。
我已经解决了使用DomSanitizer和MatIconRegistry库将SVG图标添加到app.component.ts的问题。
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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() { } } |
然后在组件的html中添加图像,如下所示:
myComponent.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <ul> <li> <mat-icon svgIcon="icon-1"></mat-icon> <span>Icon 1</span> </li> <li> <mat-icon svgIcon="icon-2"></mat-icon> <span>Icon 2</span> </li> <li> <mat-icon svgIcon="icon-3"></mat-icon> <span>Icon 3</span> </li> </ul> |