2017-02-22 127 views
4

我是angular2中的新成員。我的代碼是這樣的:訪問Angular 2中的DOM元素並更改元素的類屬性

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

@Component({ 
    selector: 'main', 
    template: ` 
    <div class="current"> 
    </div> 
    ` 
}) 

export class MainComponent implements OnInit { 
    ngOnInit(): void { 
    //change the div class from current to next... 
    } 
} 

我想將div類從'current'更改爲'next'。

如果你讓我知道什麼是最好的方式嗎?

回答

5

一個選項是使用template reference variable

在下面的示例中,將參考變量#target添加到所需元素,然後使用decorator @ViewChild@ViewChild('target') target)可以訪問組件中的變量。

從那裏,您可以通過訪問變量上的nativeElement property來獲取對DOM元素的引用。

這裏就是類的名字被更新的例子:

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

@Component({ 
    selector: 'main', 
    template: ` 
    <div #target class="current"> 
    </div> 
    ` 
}) 
export class MainComponent implements AfterViewInit { 
    @ViewChild('target') target; 

    constructor() { } 

    ngAfterViewInit(): void { 
    let element = this.target.nativeElement; 

    element.className = 'next'; 
    } 
} 

然而,值得指出的是,你可以處理大多數的DOM操作與內置的DOM指令。在這種情況下,您可以使用ngClass directive將變量綁定到類屬性:

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

@Component({ 
    selector: 'main', 
    template: ` 
    <div [ngClass]="targetClass"> 
    </div> 
    ` 
}) 
export class MainComponent implements AfterViewInit { 
    private targetClass: string = 'current'; 

    constructor() { } 

    ngAfterViewInit(): void { 
    this.targetClass = 'next'; 
    } 
} 
+0

感謝Josh爲您做出的快速響應。它的工作很好。 – mohsen

+0

爲什麼你建議'@ViewChild('target')target;'而不是顯式類型的@ViewChild('target')目標有什麼特別的原因:QueryList ;'? –

+0

你也可以使用@HostBinding('class')私有targetClass來處理類的變化。 –