Adding multiple styles to a directive in Angular 6 can be achieved by using the addClass method. It is important to note that the

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');
}

Answer №1

One of the most efficient ways to achieve this is by utilizing addClass() and removeClass(). This method allows for easy customization through CSS adjustments at a later time.

To explore further on how to implement this approach, refer to the Angular Renderer documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Content is the main driver for CSS Flexbox dynamic aspect-ratio code

When creating a grid layout for a webpage, I opted to use Flexbox. My goal was to incorporate some automatic functionality so that additional grid boxes could be included without the need to manually add classes or styles in the HTML code. One particular f ...

What could be causing the lack of styling in my Express application?

The styles are not rendering correctly on the specified route: 'http://localhost:5000/exams/add-new' However, they are working fine on the following routes: 'http://localhost:5000' 'http://localhost:5000/exams' 'http:// ...

Guidelines on Implementing a Three-Level Jquery Accordion Menu

Here is a snippet of jQuery code that I am working with: $(document).ready(function(){ $("#accordion2 h3").click(function(){ //slide up all the link lists $("#accordion2 ul ul").slideUp(); //slide down the link list below the h3 clicked - only ...

Change the width of <p> element to control the number of lines visible on the screen

Is there a way to adjust the width of specific paragraph elements so they automatically have two lines with the same width? Even when the text is longer, the width should adjust to ensure both lines are equal in length (with the last line not wider than t ...

gist-react: containing gist within a scrollable div

Struggling to contain a gist within a div with scrollbars on my next.js site using gist-react. It seems like my CSS is being overridden when the gist loads from the underlying dependency. Is there a way to achieve this without modifying the dependency itse ...

Angular2: Implement a feature to append textbox input to a span element upon button click

I'm completely new to Angular2 and I could really use some assistance with the following task. I need to take the input from a textbox and add it to a span in HTML. The requirement is to only make changes in the .ts file. I'm having trouble figu ...

Extracting information from PrimeNG datatable

Having trouble with enabling a feature where users can delete rows from a table populated after a search. The "Delete" button is not functioning as expected. Check out my table here: https://github.com/BillyCharter87/Tech-O-Dex-UI/blob/58ba15188a490a9c867 ...

Retrieve JSON information from an API using Angular 2

I am facing an issue with retrieving JSON data from an API that I created. Despite using Angular code to fetch the data, it seems to be unsuccessful. Here is the code snippet: getBook(id: string){ return this._http.get(this.url + 'books/' + ...

Exploring Angular (5) http client capabilities with the options to observe and specify the response type as 'blob'

Situation: I'm facing a challenge in downloading a binary file from a backend system that requires certain data to be posted as JSON-body. The goal is to save this file using File-Saver with the filename specified by the backend in the content-disposi ...

Are there any available tools or scripting methods for accommodating various vendor prefixes?

My preference is to use standard CSS rules for different styles that include various vendor prefixes. To test, I would start with the following: border-radius: 5px; box-shadow: 0px 0px 4px 0px #fff; transform: rotate(90deg); For the final version, I woul ...

choose image for select box background

Similar Question: Background Image for Select (dropdown) does not work in Chrome I am trying to update the background image of a select box to https://www.google.com/images/nav_logo101.png Currently, I am using the following code: <form> & ...

Pseudo-element placed beyond the parent's boundary prematurely causes premature wrapping of the line

I've implemented a basic tooltip feature on my website using the tooltip attribute and an ::after pseudoelement. The issue I'm facing is that the pseudoelement wraps to the size of its parent element because it's positioned outside. Is there ...

How can I maintain my bottom navigation bar in Bootstrap 3 without using a 3 span icon?

Hey everyone, I'm still getting the hang of MVC as I only started using it around 3 weeks ago. Currently, I am working on a Web Application where I am trying to implement a specific feature: At the bottom of the page, I have a navbar with some Html. ...

Can you use "or" or "not" syntax with CSS input type selectors?

In the world of programming, if they actually exist, Suppose I have created an HTML form with the following input fields: <input type="text" /> <input type="password" /> <input type="checkbox" /> I wish to style all input fields that a ...

Transferring extensive data from AgGrid to Clipboard

Hello, I am encountering an issue with a large triangle data set (300x300) in ag-Grid. While I am able to export it to CSV/xls without any problems, I am unable to copy and paste the data using Ctrl+A and Ctrl+C/Ctrl+V. Strangely enough, this functionali ...

Styling the elements that are next to each other using CSS

Hey there, what if I have HTML elements structured like this: <div> <div>Name</div> <div><input type="text" class="check"> <div>Age</div> <div><input type="number" class="check"></div> ...

Guide to customizing the value appearance in tooltip axispointer chart (angular)

Check out the code snippet here: https://stackblitz.com/edit/angular-ngx-echarts-zn8tzx?file=src/app/app.component.ts view image description I am looking to format and add the text "UPLOAD" and "DOWNLOAD" below the date and time. For instance: 2020-02- ...

Ways to ensure a video completely fills the frame

I am experiencing an issue where the video in the main div of my home page does not fully fill the div right away - I have to refresh the page for this to happen. As a result, there is black space on the left and right sides. Interestingly enough, this pr ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

How can we effectively merge information from different sources within a single service?

Trying to troubleshoot a complex issue here: I have an array of sidebar items that need to be merged from two different sources. One source is in the front-end code base, focusing on visual aspects like icon class and URL, while the other source is the dat ...