2016-09-26 94 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; 
    } 
} 
相關問題