0

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);
}
3
  • 1
    You can use [ngClass] to do this. More docs: stackoverflow.com/questions/35269179/… Commented Feb 4, 2019 at 8:45
  • @Jacopo Sciampi onclick i want to change the color Commented Feb 4, 2019 at 9:02
  • You should understand why, not copy-pasta the solution without understanding the reasons. Commented Feb 4, 2019 at 10:47

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.