I have directive which does an action when I scroll.
@HostListener('window:scroll')
doSomething() {
console.log(this.el);
console.log(this.el.nativeElement);
if (window.pageYOffset > 10) {
console.log('mouse scroll blahblah');
this.renderer.setStyle(this.el.nativeElement, 'height', '45px');
} else {
this.renderer.removeStyle(this.el.nativeElement, 'height');
}
}
But I want to also add background color to this element AND other styling to element which is in another component. How to do it? Is it possible to add something like
this.renderer.setStyle([
element1 [ 'height', '45px], ['background-color', 'red']
],
[
element1, 'background-color', 'blue'
]
Or maybe I should use something totally different from 'setStyle'? I know that my example is messed up but I think there may be something alike, I mean... We are not suppouse to write
this.renderer.setStyle(this.el.nativeElement, 'height', '45px');
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'red');
etc? Or maybe I shouldn't even try to do it and simply add a class as it's only proper way to add multiple styles? But how? document.getElementsByClassName('element2') add some class
Got it
Actually I'm not sure that there is one good way to do it. Even in bigger project I can't avoid mixing setting and removing single style with classes. So I wouldn't stick to only one of them. I would definitely not use only setStyle as Kevin suggested as it is terrible to remove later. Yeah, it lets you to adjust everything independently but you can do it simpler, most of the time you won't even need control specific style of element, if - then use class, remove it, if you need to remove single part do it by setStyle/removeStyle.
If you have small project then you can use whatever you want. If it's big... Well, most probably it won't be clean at some point anyway, so mix what works for you :P
const sth = document.getElementsByClassName('myElement');
if (window.pageYOffset > 10) {
this.renderer.addClass(sth[0], 'onScroll'); //for some reason there is array created, so you have to get there by adding [0]
this.renderer.addClass(this.el.nativeElement, 'onScroll');
} else {
this.renderer.removeClass(this.el.nativeElement, 'onScroll');
this.renderer.removeClass(sth[0], 'onScroll');
}