wstudiokiwi
wstudiokiwi

Reputation: 900

Ionic 2: How to add Class from Controller

How to add dynamic Class to BODY from Controller in Ionic 2? My code:

import { Component } from '@angular/core';

@Component({
  templateUrl: 'pages.html'
})
export class PagesPage {

  constructor() {

  }

  addClass() {

    //This ADD CLASS in tag BODY

  }

}

Upvotes: 2

Views: 6297

Answers (1)

Ram_T
Ram_T

Reputation: 8484

In angular 2 we use references to get elements.

<div #reference_id></div>

add extra imports

import {ElementRef, Renderer2, ViewChild, AfterViewInit} from '@angular/core';

in class

 export class App implements AfterViewInit{
    @ViewChild('reference_id') elem:ElementRef;
    constructor(private rd: Renderer2) {}
    ngAfterViewInit() {
          console.log(this.rd); 
          console.log(this.elem.nativeElement);
          this.rd.addClass(this.elem.nativeElement, 'new_class_name'); // this adds the class 
    }
}

UPDATED ANSWER

Here working plunker.

Inspect element i.e., Hello in the plunker result to check added class i.e., new_class

Upvotes: 3

Related Questions