Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove or add class in Angular

I have a list and the plugin (dragula) I used, adds certain CSS class on certain action. I am using Angular 5. I want to find out the presence of certain class (myClass) and remove that and replace with (yourClass). In jQuery we can do that like this

$( "p" ).removeClass( "myClass" ).addClass( "yourClass" );

How can I achieve this in Angular5. Here the main issue is that myClass is added automatically to the selected li by the plugin. So using a function I cant set the class.

When I tried with renderer2, it is removing the CSS class and adding another class. But it is adding only to the first li. My code is:

let myTag ; 
myTag = this.el.nativeElement.querySelector("li");
this.renderer.addClass(myTag, 'gu-mirrorss')
this.renderer.removeClass(myTag, 'dragbox');
<div  class="right-height" id ='dest' [dragula]='"second-bag"' [dragulaModel]="questions"> 
       {{ questions.length == 0 ? ' Drag and drop questions here ' : ' '}}
       <li #vc  data-toggle="tooltip" data-placement="bottom" title= {{question.questionSentence}} class="well dragbox"  *ngFor="let question of questions; let i = index" [attr.data-id]="question.questionId" [attr.data-index]="i" (click)="addThisQuestionToArray(question,i, $event)" [class.active]="isQuestionSelected(question)"  #myId > {{question.questionId}} {{question.questionSentence}}</li>
</div>
like image 261
Senchu Thomas Avatar asked Feb 22 '18 10:02

Senchu Thomas


People also ask

How do you add or remove a class?

How to use addClass() and removeClass() to remove one class name, and add a new class name. Using a function to remove a class from the selected elements.

How do I delete a class in angular 10?

$( "p" ). removeClass( "myClass" ). addClass( "yourClass" );

How do I delete a class in ngClass?

In ngClass directive either you can just pass the $scope variable which contains the classes or use the expressions to add or remove the class. ng-class="{class-name: expression1, class-name: expression2, ...}"


1 Answers

Import ElementRef from angular core and define in constructor then try below code:

Below line of code will give you first occurrence of <p> tag from Component. querySelector gives you first item and querySelectorAll gives you all items from DOM.

import { Component, ElementRef } from "@angular/core";

constructor(private el: ElementRef) {
}

let myTag = this.el.nativeElement.querySelector("p"); // you can select html element by getelementsByClassName also, please use as per your requirement.

Add Class:

if(!myTag.classList.contains('myClass'))
{
    myTag.classList.add('myClass'); 
}

Remove Class:

myTag.classList.remove('myClass'); 
like image 158
Sandip - Frontend Developer Avatar answered Sep 17 '22 17:09

Sandip - Frontend Developer