在Angular中删除或添加类

在Angular中删除或添加类

本文介绍了在Angular中删除或添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表和我使用的插件(dragula),在某些操作上添加了某些CSS类.我正在使用Angular5.我想找出某个类(myClass)的存在并将其删除并替换为(yourClass).在jQuery中,我们可以这样做

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" );

如何在Angular5中实现这一目标.这里的主要问题是myClass由插件自动添加到选定的li中.因此,使用函数我无法设置类.

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.

当我尝试使用renderer2时,它将删除CSS类并添加另一个类.但是它仅添加到第一个li中.我的代码是:

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>

推荐答案

从角形芯导入ElementRef并在构造函数中定义,然后尝试以下代码:

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

下面的代码行将为您提供Component中第一次出现的<p>标记. querySelector给您第一项,querySelectorAll给您DOM中的所有项目.

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.

添加课程:

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

删除课程:

myTag.classList.remove('myClass');

这篇关于在Angular中删除或添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:12