Apply CSS styles conditionally to an Angular component

Depending on the variable value, I want to change the style of the p-autocomplete component.

A toggle input determines whether the variable is true or false.

  <div class="switch-inner">
     <p [ngClass]="{'businessG': !toggle }" class ="toggle-inline ">Business group</p>
     <div class="toggle-btn toggle-inline">
        <label class="switch">
        <input type="checkbox" [(ngModel)]="toggle">
        <span class="slider round"></span>
        </label>
     </div>
     <p [ngClass]="{'borrower': toggle }" class="toggle-inline">Borrower</p>
  </div>

I then use this value to set the background color of my suggestion items on hover.

Currently, I am using a default color which I have customized using ::ngdeep.

::ng-deep .ui-autocomplete-list-item:hover{
    background-color: #24B3C7; // would change this to another color
    font-family: 'BNPPSans';
    border-radius: 0
}

The background color will be changed based on the value of the toggle variable.

Below is my component's HTML:

<div class="container" id ="inputSearchPage">
<div class="search-input col-md-6 col-sm-6 ui-fluid" >
   <p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"
   emptyMessage={{noBorrowerResult}} 
   [minLength]="3"
   [size] = "40"
   field = "name"
   >
   <ng-template let-elm pTemplate="item" class="suggestion-item" >
      <div >{{elm.name}} ( ID: {{elm.code}} )</div>
      <div class="add-button">+</div>
   </ng-template>
   </p-autoComplete>
</div>

How can I dynamically set the background color based on the toggle value? (If true, set

::ng-deep .ui-autocomplete-list-item:hover
background-color to color 1, else set it to color 2)

Answer №1

If you want to apply styles conditionally in Angular, you can utilize ngStyle. However, keep in mind that there is currently no built-in support for hover effects. As a workaround, you will need to use mouseenter and mouseleave events.

To achieve this, modify your html as follows:

[ngStyle]="(hover && toggle) ? { 'background-color': 'someColor' } : { 'background-color': 
'anotherColor' }" (mouseover)="hover=true" (mouseleave)="hover=false"

Answer №2

A great technique is to implement hostListeners for the events 'mouseenter' and 'mouseleave'

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

What could be causing my TypeScript project to only fail in VScode?

After taking a several-week break from my TypeScript-based open-source project, I have returned to fix a bug. However, when running the project in VScode, it suddenly fails and presents legitimate errors that need fixing. What's puzzling is why these ...

"Is there a way to transfer a value from one list box to another without needing to refresh the page, by utilizing AJAX,

Is there a way to automatically load Related Course levels in the Course Level Listbox when selecting a Course from the Course list? <script type="text/javascript" src="js/jquery.js"></script> <div>Course:<select name="course_id" id= ...

Dealing with an AWS S3 bucket file not found error: A comprehensive guide

My image route uses a controller like this: public getImage(request: Request, response: Response): Response { try { const key = request.params.key; const read = getFileStream(key); return read.pipe(response); } catch (error ...

Incorporating TypeScript into a project that already contains .js files

I currently have a NodeJS project with .js files written in ES6. I am interested in integrating typescript into this existing project. What steps should I follow? Can I simply introduce .ts files within the same directory structure? One issue I have encou ...

The styles are not being rendered on the Angular application

I have successfully implemented a Modal service with working HTML/CSS (Check it out on StackBlitz) div.cover { align-items: center; background-color: rgba(0, 0, 0, 0.4); bottom: 0; display: flex; justify-content: center; left: 0; ...

Printing HTML to a VueJS page is simple and efficient

I have a situation where one of my attributes in a property contains an HTML string. Instead of rendering the HTML as expected, when I output it within my template, the browser displays the raw HTML code with tags intact. It doesn't interpret it as a ...

Implementing ngClass with a dynamic ID in the URL condition

I am attempting to create an ngClass condition that adds an active class to a list element. Specifically, I want it to work for both the URLs '/companies' and '/company/:id'. The issue I am facing is that the current setup does not fun ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...

The scaling feature in CSS does not function properly in Internet Explorer 8

I've tried multiple approaches to transform the IE Matrix, but I'm facing an issue with the transform scale CSS not functioning in IE8. Code: .fture_box ul li.fture_img img{ width: 451px; height: 284px; display: block; margin: 0 0px 0 11px; pad ...

Creating a dropdown button in HTML table cells with JavaScript: A comprehensive guide

I'm attempting to create a drop-down button for two specific columns in my HTML table, but all the rows are being converted into drop-down buttons. I only want the "categorycode" and "categoryname" columns to be drop-down. $(document).ready(functio ...

Is app.component.ts necessary in an Angular 2 project?

Currently diving into Angular 2 and have a burning question on my mind. Do I really need the app.component.ts file in my project? Each of my folders has its own component and template, so I'm debating if the main component is necessary or if I can rem ...

Can you explain the distinction between Reflect.getMetadata and Reflect.getOwnMetadata?

Just like the title says, the reflect-metadata API comes with a method called getMetadata and another called getOwnMetadata. Can you explain the distinction between them? The same question applies to hasOwnMetadata, and so on. ...

Establish a connection between two ionic and angular applications using a node server

Currently, I am managing two Ionic applications that both interact with the same API hosted on a node server. My goal is to enable one app to send a post request and have the other app receive and utilize the information from that request. I was consider ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

Adjust the checkmark color of MUI Checkbox

When using Material UI's MUI library for React, I encountered an issue with the checkbox checkmark color. By default, the checkmark takes on the background color of the container element, which is great for light backgrounds but not ideal for dark one ...

The Chrome browser is not displaying the Ajax loader

I've been using a please-wait .gif image for my ajax loader, and it was working perfectly in Chrome until recently. There hasn't been any changes to the image itself, and it still displays correctly in IE, Mozilla, and other browsers. I'm p ...

Trigger an Angular2 component function from an HTML element by simply clicking a button

I'm just starting out with TypeScript and Angular2 and encountering an issue when trying to call a component function by clicking on an HTML button. When I use the **onclick="locateHotelOnMap()"** attribute on the HTML button element, I receive this ...

There seems to be an issue with the type error regarding the return of the mysql2/promise

As I delve into using the mysql2/promise library with Typescript, I've encountered a puzzling issue regarding the return type of the query method. Despite my best efforts, I can't seem to resolve an error in my code. Here is a snippet from my c ...

Switch the view to a grid layout upon clicking

Using bootstrap 5, I've successfully created a list view: <div class="col"> Click to switch to grid/list </div> Below is the content list: <div class="row mt-3 list"> list view ... ..... ....... </div ...

obtain an inner element within a container using the class name in a div

I am attempting to locate a span element with the class of main-tag within a nested div. However, I want to avoid using querySelector due to multiple elements in the HTML file sharing the same class and my preference against using IDs. I realize there mig ...