user3607282
user3607282

Reputation: 2555

How do I add a class to the element using a directive in Angular 2?

My functionality is that when the device is landscape it will add a class to the div and when it's portrait that class will get removed.

This is what I have implemented so far -

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

And on the code,

protected myclass:boolean;

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

This works perfectly. But I need this functionality in several other places.

So what I thought I'd do is create a directive for which I will pass the class name and for that class name to get added to that element if the conditions are satisfied.

Expected functionality:

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

And in the directive

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

Output:

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

I'm using Angular 2 RC 4. I'm new to Angular so any help is appreciated.

Upvotes: 1

Views: 3565

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657446

There is no way to use Angular2 bindings to add/remove classes with dynamic names but you can use code like below to do it in an angulary way:

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

Upvotes: 4

Related Questions