在Angular 10中展示所有Angular Material Icons的下拉列表
在Angular 10中实现Material Icons下拉选择列表
你的代码拿不到图标列表,核心原因有两个:
_iconSetConfigs是MatIconRegistry的私有内部属性,Angular版本迭代或内部实现变更都会导致这个属性失效,完全不适合生产环境使用;- 默认情况下MatIconRegistry不会预加载所有Material Icons的名称,只有手动注册过的图标才会出现在这个集合里,所以你的数组为空是正常现象。
下面给你两种可靠的解决方案:
方案一:使用官方图标名称库(推荐)
Material Design Icons提供了官方npm包,内置所有图标的名称和SVG资源,直接引入就能拿到完整列表:
- 安装兼容Angular 10的依赖
npm install @material-design-icons/icons@5.5.0 --save
- 在组件中导入并处理图标列表
import { Component } from '@angular/core'; import { icons } from '@material-design-icons/icons'; @Component({ selector: 'app-icon-selector', templateUrl: './icon-selector.component.html' }) export class IconSelectorComponent { // 提取所有图标名称 iconList = Object.keys(icons); selectedIcon: string; }
- 模板中实现带预览的下拉列表
<mat-form-field appearance="fill"> <mat-label>选择图标</mat-label> <mat-select [(value)]="selectedIcon"> <mat-option *ngFor="let iconName of iconList" [value]="iconName"> <mat-icon>{{ iconName }}</mat-icon> <span>{{ iconName }}</span> </mat-option> </mat-select> </mat-form-field>
方案二:自定义图标名称JSON文件
如果不想额外引入npm包,可以手动整理图标名称列表存为JSON文件使用:
- 从Material Icons官方平台收集所有图标名称,整理成
assets/icon-names.json:
["account_circle", "add", "alarm", ...]
- 在组件中通过HttpClient加载这个文件
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-icon-selector', templateUrl: './icon-selector.component.html' }) export class IconSelectorComponent implements OnInit { iconList: string[] = []; selectedIcon: string; constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get<string[]>('/assets/icon-names.json').subscribe(names => { this.iconList = names; }); } }
- 模板代码和方案一完全一致
关于你原有方法的补充说明
如果非要通过MatIconRegistry获取,需要先注册完整的Material Icons SVG sprite(而非单个图标),这样_iconSetConfigs里才会有names属性。但这种方法依赖私有属性,随时可能失效,绝对不推荐在生产环境使用,示例代码仅作参考:
import { Component, OnInit } from '@angular/core'; import { MatIconRegistry } from '@angular/material/icon'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-icon-selector', templateUrl: './icon-selector.component.html' }) export class IconSelectorComponent implements OnInit { iconList: string[] = []; constructor( private matIconRegistry: MatIconRegistry, private sanitizer: DomSanitizer ) {} ngOnInit(): void { // 先注册完整的Material Icons sprite this.matIconRegistry.addSvgIconSetInNamespace( 'material', this.sanitizer.bypassSecurityTrustResourceUrl('https://fonts.gstatic.com/s/i/materialiconsoutlined/v109/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2') ); // 延迟获取(注册是异步操作) setTimeout(() => { const configs = (this.matIconRegistry as any)._iconSetConfigs; configs.forEach((config: any) => { if (config.names) { this.iconList.push(...config.names); } }); }, 1000); } }
内容的提问来源于stack exchange,提问作者shutsman
相关产品推荐
相关产品推荐

