[英]How to declare HTMLElement variable outside of a function in Angular component.ts?
我想聲明 HTMLElement 變量對給定 class 中的所有函數可見,但是由於某種原因我無法這樣做。 在構造函數之前聲明它然后在構造函數中分配它的值的方法不起作用,但是當我在 function 中聲明並分配它時,例如 employeesClick() 它可以工作。
我試圖避免使用相同代碼的多個實例,因為我需要根據單擊的按鈕更改其他按鈕。
沒有錯誤,但沒有任何反應。 我該怎么做呢?
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";
}
}
您可以使用@ViewChild
指令。 只需為按鈕創建一個引用並在您的.ts
文件中獲取一個元素。
例如,html 看起來像:
<button #btn> ... </button>
在您的.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";
}
buttonRef
是 class 中的全局變量,您可以在需要的地方使用它。
不要忘記從@angular/core
導入ViewChild
和ElementRef
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.