Rosa Mystica
Rosa Mystica

Reputation: 263

add and remove class in typescript

I am developing an angular5 application. I have an array containg list of question and I displayed it by iterating using ngFor.User can select questions of his choice by pressing ctrl key. After selecting a question by pressing ctrl key that will shown as selected (I implemented that by adding that question to an array and check at the time of iteration that perticular question is in selectedQuestions array.If that is present in that array I addedan 'active' class to display it as selected).Now I want to remove this class at the time when the user dragged the mouse to drag and drop questions to reorder it(I am using ng2-dragula for drag and drop). I have tried this following code

 import {Component, OnInit, ViewChild} from '@angular/core';
 export class SummaryComponent implements OnInit {
 @ViewChild("myLabel") lab;

 addThisQuestionToArray(person: any, i: number, event) {
  if (!event.ctrlKey) {
   this.selectedQuestions = [];
  }
  this.toggleItemInArr(this.selectedQuestions, person);
 }
  toggleItemInArr(arr, item) {
  const index = arr.indexOf(item);
  index === - 1 ? arr.push(item) : arr.splice(index, 1);
 }

 isQuestionSelected(question: any) {
   return (this.selectedQuestions.indexOf(question) !== -1);
 }
 constructor(private dragula: DragulaService){
 }
 ngOnInit() {
 this.dragula
  .drag
  .subscribe(value => { 
      this.dragging =true;  
      console.log("dragging");       
      this.lab.nativeElement.classList.remove("active");
  });
 }
}

HTML code summarycomponent.html is

  <li class="well dragbox"  *ngFor="let question of questions; let i = index" [attr.data-id]="question.QuestionId"  question.firstName= "i" [attr.data-index]="i" (click)="addThisQuestionToArray(question,i, $event)" [class.active]="isQuestionSelected(question)"  #myLabel > {{i}} {{question.QuestionId}} {{question.Question}}</li>

Upvotes: 2

Views: 6680

Answers (1)

Iancovici
Iancovici

Reputation: 5731

You can control element's class with ngClass, and create a conditional statement, so if you create a variable locally like dragging, and have a class you want to conditionally apply like active

<li class="well" [ngClass]="{'active': dragging}">

alternatively

<li class="well" [ngClass]=" dragging ? 'active': '' ">

Upvotes: 1

Related Questions