Z
Z
zachfischer2018-06-28 06:42:32
JavaScript
zachfischer, 2018-06-28 06:42:32

How to make an element active on click?

There is this list:

<div class="list-group" >
  <div class="media" *ngFor="let user of users">
    <a class="list-group-item active" >
      <h4 class=" media-heading list-group-item-heading"> {{user.name}} </h4>
      <div class="row">
        <div class="col-md-12">
          <p class="list-group-item-text">{{user.position}}</p>     
        </div>
       </div>      
     </a>
   </div>
</div>


When I use such a class, list-group-item activethe entire list becomes active, but how can I make it so that only the one on which is selected becomes the active element in the list?

$('.list-group').find('.list-group-item').on('click', function () {
      if ($(this).hasClass('active')) {
          return;
      }
      $('.list-group').find('.list-group-item active').removeClass('active');
      $(this).addClass('active');
 });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-06-28
@zachfischer

You don't need jquery here if you're already using angular. Add a property to the component that will contain a link to the selected object and set its value on click. Add a class to the elements if the selected object is the same as the current one:

<div
  *ngFor="let user of users"
  [class]="active === user ? 'active' : ''"
  (click)="active = user"
>

For example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question