首页 > 解决方案 > 从 ngFor 循环中的元素覆盖“id” - AngularJS

问题描述

我正在尝试输出一个侧边栏菜单,该菜单通过包含来自 fonts.googleaplos.com 的图标名称的对象进行迭代 (*ngFor)。我希望图标以黑色背景显示为白色,当我单击它们时,将其反转(白色背景,黑色图标颜色)。单击图标时突出显示(背景变为白色)有效,但图标颜色不会改变。有没有办法单独更改所选的图标颜色?我试图更改所选图标的 id,但似乎无法覆盖 id="white-icon"。

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

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent{
  
  selectedIndex: number;

  icons: any[] = [
    {
      "name": "home"
    },
    {
      "name": "question_answer"
    },
    {
      "name": "videocam"
    },
    {
      "name": "description"
    },
    {
      "name": "event"
    },
    {
      "name": "check_circle"
    }
  ];

  public setRow(_index: number) {
    this.selectedIndex = _index;
  }

  constructor() { }

  ngOnInit(): void {
  }

}

.mat-sidenav-container {
    position: fixed;
    height: 70%;
    width: 64px;
}
.mat-sidenav{
    background-color: rgb(87, 87, 146);
}
#white-icon {
    color: white;
}
.highlight {
    background-color: white;
    color: black;
}
<head>
  <link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet">
</head>
<mat-sidenav-container>
    <mat-sidenav mode="side" opened="true">
      <!-- sidenav content -->
      <mat-nav-list>
        <div >
          <a *ngFor="let icon of icons; let i = index;" (click)="setRow(i)" [ngClass]="{'highlight': selectedIndex === i}" mat-list-item >
            <mat-icon mat-list-icon class="material-icons-round">{{ icon.name }}</mat-icon>
          </a>
        </div>
      </mat-nav-list>
    </mat-sidenav>

标签: angularjsangularjs-directive

解决方案


推荐阅读