Sam
Sam

Reputation: 1381

OnClick change the background color using Angular

I have the ul tag when the user clicks on the list the background color has to change to some other color.I am using Angular7 and am new to this. how can i achieve this.

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);
}

Upvotes: 0

Views: 11829

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

Give this a try:

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

And in your TS Class:

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;
  }

}

Here's a Working Sample StackBlitz for your ref.

Upvotes: 5

Related Questions