2017-02-22 3 views
4

저는 angular2에서 새롭게 변경되었습니다. 내 코드는 다음과 같습니다 :각도 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 조작을 처리 할 수있는 지적 가치 : 여기

클래스 이름이 업데이트 예입니다. 이 경우 을 사용하여 클래스 속성을 사용하여 변수를 바인딩 할 수 있습니다.

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

감사합니다. 빠른 답변입니다. 그것은 아름답게 작동합니다. – mohsen

+0

명시 적으로 입력 한'@ViewChild ('target') 대상 대신'@ViewChild ('target') target;을 제안한 특별한 이유가 있습니다 : QueryList ; –

+0

@HostBinding ('class') private targetClass를 사용하여 클래스 변경을 처리 할 수도 있습니다. –

관련 문제