하나의 옵션은 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';
}
}
감사합니다. 빠른 답변입니다. 그것은 아름답게 작동합니다. – mohsen
명시 적으로 입력 한'@ViewChild ('target') 대상 대신'@ViewChild ('target') target;을 제안한 특별한 이유가 있습니다 : QueryList; –
@HostBinding ('class') private targetClass를 사용하여 클래스 변경을 처리 할 수도 있습니다. –