Angular 2 - Select clicked list item (Add 'active' class and remove from siblings)

angular 6 add class to element on click
angular 4 add class onclick
ngclass
angular list onclick
apply class on click angular 2
angular list of objects
add remove class on click angular
on click add css angular

I have list items as follows in below code snippet. On mouse click I would like to select that item (add 'active' class and deselect if any other items (siblings) selected by remove'active class. I have achieved the same using jQuery (full code below). How I can achieve the functionality in Angular 2 way.

Code snippet:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<ul id="grouplist" class="list-group">
    <li class="list-group-item">Item1</li>
    <li class="list-group-item">Item2</li>
    <li class="list-group-item">Item3</li>
    <li class="list-group-item">Item4</li>
    <li class="list-group-item">Item5</li>
    <li class="list-group-item">Item6</li>
    <li class="list-group-item">Item7</li>
    <li class="list-group-item">Item8</li>
    <li class="list-group-item">Item9</li>
    <li class="list-group-item">Item10</li>
</ul>
<script>
$(function () {
    $('.list-group li').click(function() {
        $(this).addClass('active').siblings().removeClass('active');
    });
})
</script>
</body>
</html>

JSFiddle here

Angular 2 Experiment: I am able to set class via 'setElementClass'. How to remove 'active' class from siblings? Or is there any other approaches?

List view component (test1.component.html):

<h2>Select List Item</h2>

<ul id="grouplist" class="list-group">
    <li class="list-group-item" (click)="listClick($event)" *ngFor="let item of groups">
        {{ item.name }}
    </li>
</ul>

TypeScript Code (test1.component.ts):

import { Component } from '@angular/core';
import { Renderer } from '@angular/core';
import { Group } from './group';

@Component({
    selector: 'test1',
    template: require('./test1.component.html')
})
export class Test1Component {

    groups: Group[];

    constructor(private render: Renderer) {
        this.groups = [new Group("item1"), new Group("item2"), new Group("item3"), new Group("item4"), new Group("item5")];
    }

    public listClick(event: any) {
        event.preventDefault();
        this.render.setElementClass(event.target, "active", true);
        // How to remove 'active' from siblings ?
    }
}

group.ts

export class Group {
    constructor(public name: String) {
    }
}

You can use ngClass for what you are looking for:

 <ul id="grouplist" class="list-group">
     <li class="list-group-item" [ngClass]="{'active': selectedItem == item}" (click)="listClick($event, item)" *ngFor="let item of groups">
        {{ item.name }}
     </li>
</ul>

And in your listClick just set the selected item to that item:

listClick(event, newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

Make It Easy: Conditionally add class to an element on click, (With js and With out js); Add class to an element on click and remove <div> <ul​> <li *ngFor="let n of list" (click)="select(n)" [ngClass]="{active:  Update value of list item on button click in Angular 2. I have a button btnAddUpdate, a textbox and list with a edit button btnEdit in a html file. When I click on btnAdd it insert a textbox value into list and when click on btnEdit, it will display selected value in textbox and now I want to update that value in list.

You can also just pass the index of the li element to your component during a click event:

<ul id="grouplist" class="list-group">
   <li *ngFor="let item of items; let i=index" (click)="select(i)" 
       [ngClass]="{'active': selectedIndex == i, 'list-group-item': true}" >
      {{ item.text }}
   </li>
</ul>

Then let you component set its selectedIndexproperty:

@Component({
  ...
})
export class ItemListComponent {
  ...
  selectedIndex: number;
  select(index: number) {
      this.selectedIndex = index;
  }
}

The selectedIndexis used by the template to determine whether to assign the active class to the li element.

See it in this Plunker

Angular 2 - Select clicked list item (Add 'active' class and - html, I have list items as follows in below code snippet. On mouse click I would like to select that item (add 'active' class and deselect if any other items (siblings)  The easiest way to solve this problem in Angular is to do: In Template: <select [ngModel]="selectedObjectIndex"> <option [value]="i" *ngFor="let object of objects; let i = index;">{{object.name}}</option> </select> In your class: this.selectedObjectIndex = 1/0/your number wich item should be selected

For those who aren't convinced with the accepted solution and coming from an AngularJS background, here's a solution for you.

HTML:

<li *ngFor="let quality of qualities" 
    [ngClass]="quality.id === activeElement ? 'active' : 'none'"
    (click)="selectedItem(quality.id)"
    >
  {{quality.quality}}
</li>

CSS:

.active {
  background-color: #000000;
  color : #ffffff;
}

Component:

public activeElement = 1;  
public selectedItem(id) {
    this.activeElement = id;
 }

Note : My ngFor's collection is like qlist = [ { quality: 'About Me', id: 1 }] So, I'm using quality.id to switch the class, you can use your own attribute to switch. Just change the activeElement variable to whatever you want to make it default.

Display a selection list, To list them all, add an *ngFor to the <li> to iterate through the list of heroes: In this section, you'll listen for the hero item click event and update the hero detail. Here we have discussed about adding a class to an item on click. Angular 2+ ngClass Conditionally add class. Related Info. 1. Date filtering and formatting using pipe in Angular 2. 2. Simple search using pipe in angular 2. 3. Angular 2 toggle button | Angular 2 collapsible panel

<ul id="grouplist" class="list-group">
     <li class="list-group-item" [ngClass]="{'active': selectedItem == item}" 
     (click)="listClick($event, item)" *ngFor="let item of groups">
        {{ item.name }}
     </li>
    </ul>
listClick(event, newValue) {
     console.log(newValue);
     this.selectedItem = newValue;  // don't forget to update the model here
     // ... do other stuff here ...
    }

Template syntax, The following interpolation illustrates the point by adding two numbers: If the expression returns an object, including an array , it returns the same The deleteHero in (click)="deleteHero()" is a method of the data-bound It would be convenient to use two-way binding with HTML form elements like <input> and <​select> . Bind Select DropDown List in Angular 2. Cascading DropDown List using Angular 2. Don’t use hidden attribute with Angular 2. Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section. PS: If you found this content valuable and want to return the favour, then.

48 answers on StackOverflow to the most popular Angular questions, How can I get new selection in “select” in Angular 2? Angular exception: Yes that's it, in the app.module.ts, I just added : import { FormsModule } One example use case for a directive would be to log a click on an element. import {​Directive} from hall-list.component"; import {HallDetailComponent} from ". In Angular select element, the value attribute of <option> element can bind an object using property binding and one field of the object can be used to display items. For validation of select element, we need to use validation attribute such as required. We can get validation state like valid and invalid using local template variable. Select element is written using <select> tag and multiple select element uses multiple attribute as <select multiple>. By default select element compares two

AngularJS: API: select, It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions The selected values will be bound to the model as an array. Add the click event handlerlink. Rename the component's hero property to selectedHero but don't assign it. There is no selected hero when the application starts. Add the following onSelect() method, which assigns the clicked hero from the template to the component's selectedHero.

How to Add And Remove List Items From The ListView Component , Add And Remove List Items From The ListView Component in Angular ListView Within the click event, remove the list item by passing the delete icon list item to text: "Bugatti Chiron", id: "2", icon: "delete-icon" }, { text: "Bugatti Veyron Super  This tutorial is updated and compatible with all Angular versions including 6,7,8 and 9. Select/ Unselect Checkbox List Items in Angular 9. In the app.component.ts file, we will define an object of items using which we will create a list. This object will have an id, value and a boolean to check if the current item is selected or not.

Comments
  • Angular 2 or Angular 1 ? It would be good to see what you've done so far, so we can improve/correct it. This seems to be just asking us for the complete answer.
  • Angular 2 - Updated my question with my Angular 2 code.
  • Thank you, Yaser. In the given code (listClick()), please let me know how to set the selected item. Sorry if it is a basic question, I am quite new to Angular 2.
  • if i update the model object inside the click handler, how will i able to refresh the template html.
  • @Karan if by updating the model you mean item then either you need to fire an event or trigger the change detection manually
  • i love you @Yaser
  • @Yaser I've got a similar case. what if it should be used for chat list and each chat list item has (click)="GoToChatPage(chat.receiverId.username)" and opens messages on the right for that selected chat list user with you? I've posted a question here: stackoverflow.com/questions/53691060/… How can I refactor this code to fit for my issue?
  • Hi Frank, thank you for the answer. This one also works as expected. Since Yaser give the answer first, accepted that answer. Sorry, I'm able to select only one answer.
  • @Frank. Sir can you please answer my question: stackoverflow.com/questions/59154020/…