繁体   English   中英

如何在 Angular component.ts 中的 function 之外声明 HTMLElement 变量?

[英]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导入ViewChildElementRef

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM