Angular2 - Add class to item on click

angular 4 add class to element on click
how to add active class on click in angular 6
typescript toggle class onclick
typescript add class to element
how to add and remove class in angular 6
angular add class to element
angular2 add class to parent element
angular add class to form control

I have a bunch of list items and would like to highlight each one once it's clicked. This is easy for me to do in jQuery or even JavaScript but I'm lost when it comes to Angular2.

<ul>
   <li [attr.data-selected]="false" (click)="highlightItem($event)" [class.highlight]="isHighlighted($event)" *ngFor="#item of items"> {{item}} </li>
</ul>

My component

export class HelloWorld {
    items = ["pineapples", "apples", "tomatoes", "bread"];

    highlightItem(event) {
        event.target.setAttribute("data-selected", "true");
   }

   isHighlighted(event) {
       return event.target.getAttribute("data-selected") == "true";
    }
}

Not sure where my mistake is or if I'm using a wrong method


You need to make an array in your class to store highlight status of an item:

hightlightStatus: Array<boolean> = [];

Declare local variable in the template associated with ngFor:

<ul>
   <li [attr.data-selected]="false" 
       (click)="hightlightStatus[i]=!hightlightStatus[i]" 
       [class.highlight]="hightlightStatus[i]" 
       *ngFor="let item of items, let i = index"> 
       {{item}} 
   </li>
</ul>

Angular ngClass and click event for toggling class, You can then use the variable to apply a specific class to the element. Like so- addClass(event.target, class); } }. One could put this in a  Add class to an element on click and remove on click of other item and highlight the current one. (With js and With out js) Add class to an element on click and remove if we click again on the same.(With js and With out js) Let us check one by one. 1. Add class to an element on click and remove on click of other item and highlight the current one.


If I am understanding the question properly, I believe you can also use the render from angular2 to get a similar code to your example code. For my own project I did the following:

In my template I have:

<li role="presentation" (click)="userTypeSelect($event)" ><a href="#">Local</a></li>

In my component I then have:

import {Renderer} from '@angular/core';
//other imports

export class SignupComponent implements OnInit {

      constructor(private render:Renderer) { }

      userTypeSelect(event:any){
        event.preventDefault()
        this.render.setElementClass(event.target,"active",false);
      }

}

It is worth noting though that I am not using this for a list of items, however I believe it should still work.

Reference to the Renderer: Renderer Api Docs

Make It Easy: Conditionally add class to an element on click, Conditionally add class to an element on click - angular. Add class to an element on click and remove on click of other item and highlight the current one. ( With js and With out js) Add class to an element on click and remove if we click again on the same.(With js and With out js) My exporting class where i have my constructor: export class ContactInfo { constructor( public description:string) { } } Angular2 - Add item with click event.


There are many ways to achieve this, and all are very simple.

Examples:

<li *ngFor="let n of list" (click)="select(n)" [ngClass]="{active: isActive(n)}">
  <a>{{n}}</a>
 </li>

 select(item) {
      this.selected = item; 
  };
  isActive(item) {
      return this.selected === item;
  };

Only using html

<li *ngFor="let n of list" [class.active]="clicked === n" 
         (click)="clicked = n">
       <a>{{n}}</a>
    </li>

Add class on click and remove if we click on the same

select(item) {
   this.selected = (this.selected === item ? null : item); 
};

Only using html

<li *ngFor="let n of list" [class.active]="clicked === n" 
       (click)="clicked = (clicked === n ? null :n)">
     <a>{{n}}</a>
   </li>

More info

Make It Easy: Conditionally add class using Angular, I have explained about adding a class to an element on click in the previous Angular 2+Angular 4/5[ngClass][style]conditionally add class  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:


By your question title, you want to add a new class to the li when it's clicked, right?

If that's it, then it can be simple like this:

 <ul>
   <li (click)="highlightItem($event)" *ngFor="let item of items">
     {{item}}
   </li>
 </ul>

export class HelloComponent {
  public items: string = ['Apple', 'Banana', 'Pear', 'Grapes', 'Watermelon'];

  public highlightItem(event) {
    if (! event.target.classList.contains('highlighted')) {
      event.target.classList.add('highlighted');
    }
  }
}

add-css-class-on-click-in-angular-6, Toggle light/dark theme. Toggle Zen Mode. Project. Download Project. Info. Starter project for Angular apps that exports to the Angular CLI. 12.5k. 29. Files. src. 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.


It May help you

export class ContactComponent implements OnInit {

  values:Object[];


  ngOnInit() {
    this.values=[{name:'Alex',done:false},{name:'Jon',done:false}];
  }

  completed(i:number){
    if(this.values[i])
      this.values[i]['done']=!this.values[i]['done'];
  }

}

HTML:

<ul>
    <li *ngFor="let v of values;let i='index'" 
        (click)='completed(i)'
        [class.checked]="v.done" 
        >       
        {{v.name}}<span class="close">×</span>
    </li>
</ul>

What's the best way to add/remove classes from an element?, I simply want to add a class of active to which ever li is clicked and remove it This is easy to do in jQuery but not sure what the Angular 2 answer is, if there is  Angular Add and remove Active class on click ng toggle. Today, We want to share with you Angular Add and remove Active class on click ng toggle. In this post we will show you How to Add and remove active class on click using AngularJS, hear for Add Class, Remove Class or Toggle Class to div using AngularJS we will give you demo and example for implement.


How do I toggle a CSS class onClick? : Angular2, But I am having trouble toggling the CSS Class of a clicked element. In specific and just import them into multiple different Angular projects, for different "Apps". We can add a single class or multiple classes dynamically based upon the conditions. We will go through few examples to understand it further. Table of Contents. Add a Class based upon the condition; Add a class based on multiple conditions; Add multiple Classs using ngClass; Pass a method to ngClass; Add a Class based upon the condition


Angular: Toggle a Class on Click, Simple example demonstrating adding a class to an element on 'click' with Angular. var divToChange = document. getElemetById ('my_id'); //to change the class we would do. divToChange. className = "newclass"; //if we want to add multiple classes, we could just do divToChange. className = "newclass secondclass thirldclass"; //if we want to add a class name without removing the class present before, we do: divToChange. className = divToChange. className. concat (" addedwit"); //to change the background color of such an element, we would also have to do. divToChange. style


Angular2 - add class to an active element, <title>angular playground</title> <link rel="stylesheet" href="style.css" /> <script about javascript']; } select(item) { this.selected = item; }; isActive(item) { return  On this page we will provide angular 2 NgClass example. It is used to add and remove CSS classes on an HTML element. We can bind several CSS classes to NgClass simultaneously that can be added or removed. There are different ways to bind CSS classes to NgClass that are using string, array and object.