You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中无法在浏览器显示独立星星图标求助

解决Angular自定义星星图标组件不显示的问题

我帮你梳理下问题所在,一步步来修复这个星星图标不显示的问题:

1. 核心问题:子组件未声明输入属性接收父组件值

你在父组件app.component.html里给<app-star>传递了[valu]="post.valu",但自定义的star.component.ts里根本没把valu声明为输入属性,导致子组件完全接收不到父组件传来的状态值!

打开star.component.ts,添加@Input()装饰器来声明接收属性:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-star',
  templateUrl: './star.component.html',
  styleUrls: ['./star.component.css']
})
export class StarComponent {
  @Input() valu!: boolean; // 声明为输入属性,接收父组件传递的值

  onclick() {
    this.valu = !this.valu; // 别忘了在点击事件里切换状态
  }
}

2. 修复模板里的类名冲突

你的span标签里同时写了多个class属性,还混了无关的glyphicon-globe(这是地球图标,会和星星图标冲突),整理模板代码:

<!-- 移除重复class属性和多余的地球图标类 -->
<span class="glyphicon" 
      [class.glyphicon-star]="valu" 
      [class.glyphicon-star-empty]="!valu" 
      (click)="onclick()">
</span>

也可以用更简洁的NgClass语法:

<span class="glyphicon"
      [ngClass]="{'glyphicon-star': valu, 'glyphicon-star-empty': !valu}"
      (click)="onclick()">
</span>

3. 确认Bootstrap样式已正确引入

如果前面两步做完还是看不到图标,大概率是没引入Bootstrap的CSS文件。请确保:

  • 在项目的index.html中添加Bootstrap的CDN链接:
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
    
    或者通过npm安装Bootstrap后,在angular.json的styles数组里引入本地样式文件。

最后验证

重启Angular开发服务器(修改输入属性后有时需要重启生效),点击星星组件,就能看到空心/实心星星的切换效果啦!

内容的提问来源于stack exchange,提问作者Vinay VValaboju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:46:26