One of my directives triggers 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');
}
}
Now, I want to not only change the height but also add a background color to this element and apply other styles to an element in another component. How can I achieve that? Is it possible to do something like
this.renderer.setStyle([
element1 [ 'height', '45px], ['background-color', 'red']
],
[
element1, 'background-color', 'blue'
]
Alternatively, should I consider using a different method instead of 'setStyle'? I realize that my example is messy, but I believe there might be a similar solution. I mean... Shouldn't we have to write
this.renderer.setStyle(this.el.nativeElement, 'height', '45px');
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'red');
etc? Or perhaps I should simply add a class, as it's the proper way to add multiple styles? But how? document.getElementsByClassName('element2') add some class
Understood
Actually, I'm unsure if there is one perfect way to handle this situation. Even in larger projects, avoiding mixing single style settings with classes seems challenging. So, sticking to just one approach may not be practical. I wouldn't solely rely on setStyle as Kevin suggested, as it becomes cumbersome to remove later on. While it allows for independent adjustments, simpler methods can often suffice without necessitating direct control over specific elements' styles. If needed, use classes; otherwise, opt for individual setStyle/removeStyle actions.
In smaller projects, feel free to implement whichever method suits you best. For larger projects... Well, chances are it'll get messy at some point regardless. Therefore, mix and match based on 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');
}