[英]How to declare HTMLElement variable outside of a function in Angular component.ts?
I want to declare HTMLElement variables visible to all functions in given class, however i am unable to do so for some reason.我想声明 HTMLElement 变量对给定 class 中的所有函数可见,但是由于某种原因我无法这样做。 Method of declaring it before constructor and then assigning its value in constructor does not work, but when i declare and assign it in a function, for example employeesClick() it works.
在构造函数之前声明它然后在构造函数中分配它的值的方法不起作用,但是当我在 function 中声明并分配它时,例如 employeesClick() 它可以工作。
I am trying to avoid using multiple instances of same code, as i need to change other buttons based on which one was clicked.我试图避免使用相同代码的多个实例,因为我需要根据单击的按钮更改其他按钮。
There are no errors, but nothing happens.没有错误,但没有任何反应。 How do i do this?
我该怎么做呢?
export class HeaderComponent implements OnInit {
projects:HTMLElement;
constructor() {
this.projects=document.getElementById('projects');
}
ngOnInit() {
}
projectsClick(){
this.projects.style.color="#DEA731";
}
employeesClick(){
var employees : HTMLElement = document.getElementById('employees');
employees.style.color="#DEA731";
}
}
You can use the @ViewChild
directive.您可以使用
@ViewChild
指令。 Just create a reference for a button and get an element in your .ts
file.只需为按钮创建一个引用并在您的
.ts
文件中获取一个元素。
For example, html looks like:例如,html 看起来像:
<button #btn> ... </button>
In your .ts
:在您的
.ts
中:
export class HeaderComponent implements OnInit {
@ViewChild('btn') buttonRef: ElementRef;
...
someMethod(){
//do something like change a text color of your button
this.buttonRef.nativeElement.style.color = "#aaa";
}
The buttonRef
is a global variable in the class and you can use it where you need. buttonRef
是 class 中的全局变量,您可以在需要的地方使用它。
Don't forget to import ViewChild
and ElementRef
from @angular/core
;不要忘记从
@angular/core
导入ViewChild
和ElementRef
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.