首页 > 解决方案 > OnClick 使用 Angular 更改背景颜色

问题描述

当用户单击列表时,我有 ul 标记,背景颜色必须更改为其他颜色。我正在使用 Angular7 并且对此很陌生。我怎么能做到这一点。

HTML:

<ul class="horizontal" id="nav">
  <li><a class="active">Draft</a></li>
  <li><a>Planned</a></li>
  <li><a>Started</a></li>
  <li><a>Suspended</a></li>
  <li><a>Ended</a></li>
</ul>

CSS:

ul.horizontal li {
  float: left;
}

ul.horizontal {
  float: left;
  margin: 0 0 3em 0;
  padding: 0;
  list-style: none;
  background-color: #E2E2E2;
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
}

ul.horizontal li a {
  color: #000;
  display: block;
  position: relative;
  line-height: 32px;
  padding: 0 16px 0 32px;
  white-space: nowrap;
  border-right: 1px solid #ccc;
}

ul.horizontal li a.active {
  background-color: #0275E7;
  color: #ffff;
  // background-color: rgb(201, 205, 248);
}

标签: htmlcssangulartypescriptangular7

解决方案


试试这个:

<ul class="horizontal" id="nav">
  <li 
    *ngFor="let state of states"
    (click)="setStateAsActive(state)">
    <a [class.active]="state === activeState">
      {{ state }}
    </a>
  </li>
</ul>

在您的 TS 课程中:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  activeState = 'Draft';

  states = [
    'Draft',
    'Planned',
    'Started',
    'Suspended',
    'Ended',
  ]

  setStateAsActive(state) {
    this.activeState = state;
  }

}

这是您参考的工作示例 StackBlitz


推荐阅读