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

Autocomplete feature seems to be functioning properly in the online demonstration, while it does not seem

I can see that the autocomplete feature is working in the example provided, but it's not functioning properly in my attempt. What could be causing this issue? <!doctype html> <html lang="en"> <head> <meta charset="utf-8> & ...

Ways to constrain checkbox choices to only one within an HTML file as the checklist with the checkboxes is being created by JavaScript

I am working on developing an HTML dialogue box to serve as a settings page for my program. Within this settings page, users can create a list of salespeople that can be later selected from a drop-down menu. My current objective is to incorporate a checkbo ...

How does the size of a font affect the amount of screen space a character occupies in pixels?

I am currently working on a custom user interface that requires precise measurement of how many pixels are taken up by a specific string of text. My attempts to control the character size using the font-size property have been met with unexpected results. ...

Issues are occurring with the @font-face css for the Futura Bk BT Bok.ttf font file

Is there a way to incorporate the 'Futura Bk BT Bok.ttf' font into my website using the CSS @font-face rule? Here is a snippet of my current CSS: @font-face { font-family: abcd; src:url('Futura Bk BT Bok.ttf') format('true ...

An issue was encountered in the browser.js file located in the node_modules directory for the @angular/animations package

While attempting to create a data table using Angular Materials and CRUD functionalities, an error occurred after installing npm toast (ngx-toastr). The error message displayed was: ERROR in ./node_modules/@angular/animations/ivy_ngcc/fesm2015/browser.js ...

Creating a Typescript mixin function that accepts a generic type from the main class

I am working with the code snippet shown below: // Types found on https://stackoverflow.com/a/55468194 type Constructor<T = {}> = new (...args: any[]) => T; /* turns A | B | C into A & B & C */ type UnionToIntersection<U> = (U extend ...

There seems to be an issue with the CSS file linking properly within an Express application

Every time I run my app.js file, the index.html file is displayed. However, when I inspect the page, I notice that the CSS changes are not taking effect. Strangely, if I open the HTML file using a live server, the CSS changes are visible. Can someone exp ...

Tips for utilizing automatic type detection in TypeScript when employing the '==' operator

When using '==' to compare a string and number for equality, const a = '1234'; const b = 1234; // The condition will always return 'false' due to the mismatched types of 'string' and 'number'. const c = a = ...

Tips for inserting a Vue.js variable into a window.open event

Within this snippet of code: <tr v-for="person, index in People" :key='index'> <td> <button type="button" onclick="window.open('/details/'+person.id,'_blank')"> details</butto ...

Enhance PHP search functionality by showcasing hidden auto-complete suggestions in real-time

I am attempting to showcase unlisted search results that can be clicked on to redirect the user to a specific HTML page based on data retrieved from a MySQL database. My development environment is PhoneGap. Thus far, I have successfully set up a basic PH ...

The minimum height of the IE element could not fully expand within its flex container that was set to absolute positioning

Creating a webpage with a full-page layout using a content session that spans the entire height of its container is my current project. To achieve this, I have implemented the following: The content's container (div.inner) is set to be absolute-posi ...

Retrieve the generic type parameter of an interface implementation

I am attempting to extract a type parameter from an interface in order to use it as a parameter for a generic function. In my particular scenario, I have the following generic types: interface ITranslatable<T, K extends keyof T> { translations: IT ...

How can I identify and remove duplicate elements from an array of objects?

elements= [ { "id": 0, "name": "name1", "age": 12, "city": "cityA" }, { "id": 1, "name": "name2", "age": 7, "city": "cityC" }, { &qu ...

Using TypeScript, Material UI introduces a new property to the primary object on the palette

Experimenting with the customization of MUI v5 theme has been a fun challenge in my current project. I have successfully tailored the theme to suit my requirements so far, but now I am faced with the task of adding a new property to the primary object defi ...

Tips for enhancing this CSS design to resemble a table

I am a beginner in working with CSS layouts for websites and I have implemented the following code that serves my purpose. Although it is currently functional, its functionality does not necessarily mean that it is well-written. Could someone review this ...

FormView does not have a defined namespace prefix asp - How should I specify my Page Directive?

After creating a basic web page using Microsoft Expression Web 4 with an ASP Connection to a local Access DB, I encountered an error when navigating to the page from another webpage. The browser displayed the following errors: Error: Namespace p ...

There seems to be a column in the MySQL INSERT query that is unidentifiable and does not exist in the list of fields

id and cost are required as integers and cannot be left empty. I encountered the following error message: 'Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'' var sql = "INSERT INTO Paintings(` ...

Executing a jQuery function automatically & Invoking a jQuery function using the onClick attribute in an HTML element

Having some issues with jQuery and could use some assistance... Currently, I am trying to have a jQuery function automatically execute when the page loads, as well as when a button is clicked. [Previous Issue] Previously, the jQuery function would automa ...

Accessing component instances of all components declared in HTML in Angular 7

In the works is a page that acts as a form creator. Users will be able to click and insert various components onto the page, resulting in entries being added to the "component" variable like this: Take Component1 for example: const childComponent = this. ...

Creating responsive images in a navbar with HTML and CSS

I need help with this code snippet: <div> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <div class="d-flex flex-row justify-content-center align-items-center"> <a cla ...