【问题标题】:Angular [ngClass] inside *ngFor for selected item*ngFor 内的 Angular [ngClass] 用于选定项目
【发布时间】:2021-02-26 14:14:36
【问题描述】:

您好,我需要一些帮助来将 [ngClass] 设置为单击的项目。我在css文件中有课。即使组件被销毁,我也需要这种样式保留在所选项目上。我所拥有的不起作用。 scc 不适用于点击的项目。

 <ul *ngFor="let item of list$ | async" [ngClass]="{ selected: selectedSong === item }">
    <li><h5><a (click)="sentItem(item.ID)">{{ item.name }}</a></h5></li>
    <li>{{ item.description }}</li>
 </ul>

selecedSong:any;
  sentItem(ID: string) {
    this.musicService.setViewed(ID);
    this.selectedSong = ID;
    this.router.navigate(["/some-route",ID]);
  }

【问题讨论】:

  • 能否在stackbliz中给出一些代码sn-p
  • 我注意到,当页面呈现时,我在 ui 中有这个 cde:ng-reflect-ng-class="[object Object]"。如果我在 Elements 中手动添加 css 类-它可以工作。是css没有应用的问题吗?

标签: angular


【解决方案1】:

你能试试这个解决方案吗?在你的 html 文件中用 [ngClass]="{ 'selected': selectedSong === item.ID}" 这个条件替换条件。

<ul *ngFor="let item of list$ | async" [ngClass]="{ 'selected': selectedSong === item.ID }">
  <li>
    <h5><a (click)="sentItem(item.ID)">{{ item.name }}</a></h5>
  </li>
  <li>{{ item.description }}</li>
</ul>

【讨论】:

  • 谢谢,但没有任何区别。
  • 你替换html中的条件了吗?
  • 新条件是 [ngClass]="{'selected': selectedSong === item.ID}"。
【解决方案2】:

你能试试这个吗?在您的 html 文件中,使用双等号 (==) 而不是 === 替换条件 以防万一值与类型不匹配。

[ngClass]="{ 'selected': selectedSong == item.ID }">

【讨论】:

    【解决方案3】:

    这里你需要一些设计改变,首先改变 ngClass 条件,如下所示

     [ngClass]="{ 'selected': selectedSong === item.ID }"
    

    另一件事是您只是在初始化 selectedSong 但分配了任何值,因此上述条件不可能成立。

    您在 click 方法中分配值,但之后它会立即导航..

    如果您想查看差异,可以通过将值设置为 selectedSong 来观察这一点,可能是 items 的第一个元素。 p>

    编码愉快.. :)

    【讨论】:

      【解决方案4】:

      我们可以通过两种方式解决您的问题。

      第一个解决方案:

      <ul *ngFor="let item of list$ | async" [ngClass]="{ selected: selectedSong === item }">
          <li><h5><a (click)="sentItem(item)">{{ item.name }}</a></h5></li>
              <li>{{ item.description }}</li>
       </ul>
      sentItem(item) {
          this.musicService.setViewed(item.ID);
              this.selectedSong = item;
              this.router.navigate(["/some-route",item.ID]);
      }
      

      第二种解决方案:

      
      <ul *ngFor="let item of list$ | async" [ngClass]="{ selected: selectedSong === item.ID }">
          <li><h5><a (click)="sentItem(item.ID)">{{ item.name }}</a></h5></li>
              <li>{{ item.description }}</li>
       </ul>
      
      

      【讨论】:

      • 谢谢,但这些都不起作用。问题出在这里: this.selectedSong = item; selectedSong 是一个布尔值,不知何故它必须是 === ID ,而不是 item- 因为 item 无法从此组件访问。 ID 是。
      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多