[英]Angular2: Directive variable change, update element
I'm currently trying to give classes to an wrapper that contains all of my app, i usually find this handy for giving certain states like when the header is fixed, or the menu's are opened etc. 我目前正在尝试将类提供给包含我的所有应用程序的包装器,通常可以方便地给出某些状态,例如标头固定或打开菜单等。
So upon reading through some the docs of angular i should probably use an 'Directive'. 因此,在阅读了一些有关angular的文档后,我可能应该使用“指令”。 Now i got this all set up and it looks like this:
现在我已经完成了所有设置,看起来像这样:
constructor(private router:Router, @Inject(DOCUMENT) private document:Document, el:ElementRef, renderer:Renderer) {
this.setClasses(el, renderer);
}
setClasses(el:ElementRef, renderer:Renderer) {
renderer.setElementClass(el.nativeElement, 'header-fixed', this.headerFixed);
}
@HostListener("window:scroll", [])onWindowScroll() {
let number = this.document.body.scrollTop;
if (number > 100) {
this.headerFixed = true;
} else if (this.headerFixed && number < 10) {
this.headerFixed = false;
}
}
Now this is working perfectly but as you can see i'm toggling the headerFixed
variable depending on scroll position. 现在这可以正常工作,但是如您所见,我根据滚动位置切换
headerFixed
变量。 However i could of course run the function setClasses()
again and it will work but is there anyway to subscribe/watch the variable and update automatically when changed? 但是我当然可以再次运行
setClasses()
函数,它将起作用,但是无论如何,是否有订阅/监视变量并在更改时自动更新?
Or is there even a better way of achieving wat i'm trying to do? 还是有一种更好的方法来实现我正在尝试的wat?
You can use @HostBinding
like: 您可以像这样使用
@HostBinding
:
@HostBinding('class.header-fixed') get myClass() {
return someCondition;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.