Ionic 2:如何从Controller添加Class

时间:2017-06-01 08:13:51

标签: angular ionic2

如何在Ionic 2中从Controller向import { Component } from '@angular/core'; @Component({ templateUrl: 'pages.html' }) export class PagesPage { constructor() { } addClass() { //This ADD CLASS in tag BODY } } 添加动态类? 我的代码:

{{1}}

1 个答案:

答案 0 :(得分:2)

在角度2中,我们使用引用来获取元素。

<div #reference_id></div>

添加额外的导入

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

在班级

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

更新的答案

在这里工作plunker.

在plunker结果中检查元素,即 Hello ,以检查添加的类,即 new_class