【问题标题】:add and remove class in typescript在打字稿中添加和删除类
【发布时间】:2018-07-08 06:06:54
【问题描述】:

我正在开发一个 angular5 应用程序。我有一个包含问题列表的数组,我通过使用 ngFor 进行迭代来显示它。用户可以通过按 ctrl 键选择他选择的问题。通过按 ctrl 键选择一个问题后,该键将显示为已选中(我通过将该问题添加到数组中来实现这一点,并在迭代时检查特定问题是否在 selectedQuestions 数组中。如果该数组中存在该问题,我添加了一个 'active ' 类以将其显示为选中状态)。现在我想在用户拖动鼠标拖放问题以重新排序时删除此类(我正在使用 ng2-dragula 进行拖放)。我已经尝试过以下代码

 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代码summarycomponent.html是

  <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>

【问题讨论】:

  • 你的问题很难理解。您能否描述一下您想要实现的目标,什么不起作用,甚至添加一些屏幕截图/更多代码?

标签: css angular typescript ng2-dragula


【解决方案1】:

你可以用 ngClass 控制元素的类,并创建一个条件语句,所以如果你在本地创建一个变量,如dragging,并有一个你想有条件地应用的类,如active

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

或者

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

【讨论】:

  • 目前我正在使用 [class.active]="isQuestionSelected(question)" 来了解是否选择了通过的问题以了解它是否处于活动状态。通过简单地使用变量拖动我可以如何设置列表中每个项目的值是否处于活动状态
  • 为我节省了很多时间!
猜你喜欢
  • 2015-05-26
  • 2021-08-06
  • 2021-07-17
  • 2019-07-03
  • 2021-10-14
  • 2018-06-12
  • 2021-01-23
  • 1970-01-01
  • 2022-01-28
相关资源
最近更新 更多