我是 angular2 的新手。我的代码是这样的:
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 类从“当前”更改为“下一个”。
如果您让我知道最好的方法是什么,我会同意吗?
最佳答案
一个选择是使用 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使用类属性绑定(bind)变量:
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';
}
}
关于javascript - 访问 Angular 2 中的 DOM 元素并更改元素的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382033/