Apply a CSS class once a TypeScript function evaluates to true

Is it possible to automatically apply a specific CSS class to my Div based on the return value of a function?

<div class="{{doubleClick === true ? 'cell-select' : 'cell-deselect'}}"></div>

The doubleClick function will return true.

Answer №1

To apply styling dynamically, utilize the ngClass directive and remember to include the parentheses when calling the doubleClick function.

<div [ngClass]="{'cell-select': doubleClick(),'cell-deselect': !doubleClick() }">Content</div>

Alternatively, you can achieve the same result without using ngClass:

<div class="{{doubleClick() ? 'cell-select' : 'cell-deselect'}}"></div>

Answer №2

There are alternative ways to achieve the same result and avoid certain cases. Using {{func()}} or [prop]="func()", Angular evaluates the function whenever there is a UI change, such as clicking another button or typing in a textbox, which may not be directly related to the method itself.

We can invoke the function to update a property and bind that property to the ngClass directive.

template

<div [ngClass]="{'cell-select':clicked ,'cell-deselect': !clicked }" 
     (dblclick)="doubleClick()">
  Content
 </div>

component

  clicked = false;
  doubleClick() {
    this.clicked = true;
  }

You can toggle a value.

template

<div [ngClass]="{'cell-select':toggled ,'cell-deselect': !toggled }" 
     (dblclick)="toggleDoubleClick()">
  Toggle
 </div>

component

toggled= false;
  toggleDoubleClick(){
    this.toggled = !this.toggled;
  }

Check out the StackBlitz demo 👍👍

If you prefer not to create a property, you can handle all the logic in the template.

<div [ngClass]="{'db-clicked':elm.clicked}" #elm (dblclick)="elm.clicked = true">
    Double click {{elm.clicked ? ':)' : ':('}}</div> 
 <button (click)="elm.clicked = false">Reset</button>

Explore the StackBlitz demo 🚀🚀

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 is the best way to recycle a single modal in Ionic?

Apologies for the vague title, but I'm facing an issue with creating a single modal to display data from multiple clickable elements, rather than having separate modals for each element. For example, when I click on item 1, its data should be shown in ...

Help with Material-UI: Passing unique props to a custom TreeItem component

I am trying to pass an argument category to the component CustomTreeItem which uses TreeItemContent. Documentation: https://mui.com/ru/api/tree-item/ import TreeItem, { TreeItemProps, useTreeItem, TreeItemContentProps, } from '@material-ui/lab ...

How to navigate to an anchor tag on a separate page using Angular 9

Is there a way in Angular 9 to create a link that directs to a specific section on a page like I would in plain HTML using <a href="myPage#mySection">go to my section</a>? I've come across outdated solutions when searching for this, so I&a ...

Navigating to the HomePage using the nebular auth/login library with the login() function: A step-by-step guide

After setting up my Angular Project and installing the nebular library, I am working on creating 3 pages: Login, Register, and Home. I have successfully created the login and register pages using NbLoginComponent and NbRegisterComponent. Now, my goal is to ...

Steps to troubleshoot a simple function that manages asynchronous tasks

Looking to develop a versatile function that can handle async functions, execute them, and catch any errors that may arise. Coming from a javascript background, I initially managed to create a function that did just this. However, my attempt to enhance it ...

Ways to mimic an Angular subscription during a Jasmine test

I'm currently troubleshooting a unit test for my code (I'm not very experienced with Jasmine) after adding some subscriptions to a service. I'm encountering an issue where the subscriptions are coming up as undefined. I'm not entirely s ...

Is there a way to specify a type for a CSS color in TypeScript?

Consider this code snippet: type Color = string; interface Props { color: Color; text: string; } function Badge(props: Props) { return `<div style="color:${props.color}">${props.text}</div>`; } var badge = Badge({ color: &ap ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

Instantiate an object of the ng.IQService type without using injection

Is it possible to define a local variable in the controller of type ng.IQService ( private _q: ng.IQService;) without requiring injection? My technology stack includes typescript and angular. The reason for this requirement is due to existing legacy code ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

Oops! There seems to be an issue: Uncaught promise error - ReferenceError: google is not defined

I've integrated Angular 2 with Google Maps Places Autocomplete in my project, but I encountered an error: ERROR Error: Uncaught (in promise): ReferenceError: google is not defined Here's the HTML snippet: <agm-map id="googleMap"> ...

"Troubleshooting the issue of Angular's ViewContainerRef.createComponent malfunctioning on subsequent

My application is structured into Header, Context, and Content sections. I am looking to dynamically inject different components into the Context Component (viewContainerRef) based on the route and other conditions. To achieve this functionality, I have ...

React Typescript does not support the use of React-Router

I'm currently working on a React app that utilizes Typescript. The React version is set to "react": "^16.9.0", and the React-Router version is "react-router-dom": "^5.1.2". Within my App.tsx file, the structure looks like this: const App: React.FC ...

Data can be retrieved in a React/Next.js application when a button is clicked, even if the button is located in a separate

Whenever the button is clicked, my function fetches weather data for the current location. I am trying to figure out how to transfer this data from the Location component to the pages/index.tsx. This is where another component will display the data. This ...

Enhancing the design of the Mat Calendar with a stylish border

I've been attempting to put a border around my mat calendar, but I'm having trouble figuring out the specific class that will give me the exact look I want. I need it to be just like this: I tried using the following class: .mat-form-field-flex ...

`Incorporate concurrent network requests in React for improved performance`

I am looking to fetch time-series data from a rest service, and currently my implementation looks like this async function getTimeSeriesQuery(i) { // Demonstrating the usage of gql appollo.query(getChunkQueryOptions(i)) } var promises = [] for(var i ...

Angular formArray option buttons

I am currently working on incorporating a radio button group into a FormArray, but I'm encountering an issue where selecting a value changes the value for every member of the FormArray. It seems to be related to the formControlName, however, I am unsu ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

The process of extracting all arrays from a JSON object

Within my JSON object, there is a list of countries each with multiple regions stored in an array. My goal is to extract and combine all the regions into one single list. However, when I attempt to map the data, it does not consolidate all the regions as e ...