2016-09-26 91 views
1

我的功能是,当设备是风景时,它会向div中添加一个类,当它是肖像时,该类将被删除。如何使用Angular 2中的指令将一个类添加到元素中?

这是我到目前为止执行 -

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

我使用角2 RC 4 我是新以Angular,所以任何帮助表示赞赏。

+0

你应该尝试这样的“element.addClass ( 'myDraggable');” – Bharat

+0

或者这个也是'angular.element(element).addClass('myDraggable');' – Bharat

回答

4

没有办法用Angular2绑定添加/动态名称中删除类,但你可以使用如下代码下面做在angulary方式:

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; 
    } 
} 
相关问题