Angular中ngClass绑定布尔值后图标旋转无法停止问题求助
Angular中Font Awesome图标旋转无法停止的解决方案
问题根源
你的代码仅在请求成功时将loading设为false,一旦请求出错(比如服务器异常),loading会一直保持true,导致fa-spin类无法被移除,图标持续旋转。同时可以优化类绑定的写法,让逻辑更清晰。
修复步骤
- 错误回调中重置loading状态:无论请求成功还是失败,都要将
loading设为false - 优化类绑定语法:使用Angular的
[class.类名]语法替代三元表达式,写法更简洁直观
修改后的代码
HTML部分
<button mat-fab color="primary" class="float-end" (click)="load()"> <mat-icon class="fa-duotone fa-rotate-right" [class.fa-spin]="loading"></mat-icon> </button>
TypeScript部分
load(): void { this.loading = true; this.productsService.getProducts().subscribe( (response: any) => { this.dataSource = new MatTableDataSource(response.products); this.dataSource.paginator = this.paginator; this.selection.clear(); this.loading = false; }, error => { this.alertService.error('Server error in Getting Products'); this.loading = false; // 错误分支也要重置loading状态 } ); }
额外检查
确保你在组件类中正确声明了loading变量:
loading = false; // 组件内属性,初始值设为false
内容的提问来源于stack exchange,提问作者Artur
相关产品推荐
相关产品推荐

