【问题标题】:How do I add a class to the element using a directive in Angular 2?如何使用 Angular 2 中的指令向元素添加类?
【发布时间】:2017-02-03 16:59:36
【问题描述】:

我的功能是,当设备为横向时,它将向 div 添加一个类,而当它是纵向时,该类将被删除。

这是我目前已经实现的——

<div [class.landscape]="myclass"></div>

关于代码,

protected myclass:boolean;

checkLandscape() {
  this.myclass = screen.isLandscape; 
  //I have subscribed to the orientation change which will trigger this method when the orientation changes.
}

这非常有效。但我在其他几个地方需要这个功能。

所以我想我要做的是创建一个指令,我将为其传递类名,并且如果满足条件,则将该类名添加到该元素中。

预期功能:

<div myClassDirective="myclass"></div> 

在指令中

addMyClass() {
 // add class if it's landscape.
 // removed class if it's portrait.
}

输出:

<div class="myclass"></div>

我正在使用 Angular 2 RC 4。 我是 Angular 的新手,因此不胜感激。

【问题讨论】:

  • 你应该像这样尝试'element.addClass('myDraggable');'
  • 或者这个也是 'angular.element(element).addClass('myDraggable');'

标签: angular


【解决方案1】:

没有办法使用 Angular2 绑定来添加/删除具有动态名称的类,但您可以使用如下代码以有角度的方式执行此操作:

class MyClassDirective {
  constructor(private renderer:Renderer, private elRef:ElementRef) {}

  private oldClassName:String;

  @Input() set className(value:String) {
    if(oldClassName) {
      this.renderer.setElementClass(this.elRef.nativeElement, this.oldClassName, false);
    }
    if(value) {
      this.renderer.setElementClass(this.elRef.nativeElement, value, true);
    }
    this.oldClassName = value;
  }
}

【讨论】:

    猜你喜欢
    • 2014-03-08
    • 2018-08-26
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2017-12-18
    • 2013-10-17
    相关资源
    最近更新 更多