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

Typescript iterative declaration merging

My current project involves creating a redux-like library using TypeScript. Here is an example of the basic action structure: interface ActionBase { type: string; payload: any; } To customize actions for different types, I extend the base interface. ...

Steps to configure Visual Studio Code to automatically open the original TypeScript file located in the "src" folder when a breakpoint is hit in a Node.js application

I am currently working on a CLI node application and using VSCode to debug it. Everything seems to be working fine, except for one annoyance: when I hit a breakpoint, VSCode opens the source map file instead of the actual TypeScript file located in my "src ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

Angular 4: Issue with sending POST data via HTTP requests

I am currently working on developing a Web Application and I am facing an issue with testing the HTTP functions. Here is an example of my code snippet: import { Injectable } from '@angular/core'; import { Headers, RequestOptions, Http } from & ...

How do I use [(ngModel)] to set custom multiple select with 'selected' options with Angular and Materialize CSS?

Below is a snippet of code I am working with: <div class="input-field col s12"> <select name="uniqueName" [(ngModel)]="model.servicesIds" multiple> <ng-container *ngFor="let service o ...

Using ngx-translate to access JSON files stored in a server

I have been working on integrating translation key-value pairs into my system using a JSON file hosted on a server. The server holds a file called "en.json". Here is what I have accomplished so far: App Module Imports: TranslateModule.forRoot({ ...

Retrieve the data from a JSON file using Angular 4

I have a JSON data structure that looks like this: [{"id": "ARMpalmerillas07", "type": "GreenHouse","act_OpenVentanaCen": {"type": "float", "value": 0, "metadata": {"accuracy": {"type": "Float", "value": "07/02/2018 13:08 : 43 "}}}, "act_OpenVentanaLatNS" ...

Typescript is failing to perform type checking

I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet: abstract class Mammal { abstract breed(other: Mammal); } class Dog extends Mammal { breed(other: Dog) {} } class Cat extends Mammal { ...

How can I display a new module in Angular without navigating to it?

After following the tutorial at https://angular.io/guide/lazy-loading-ngmodules#create-a-feature-module-with-routing I set out to create the following: My goal is to have a dedicated module for all customer-related components accessible through the /cust ...

Tips for making use of incomplete types

Is there a way to reference a type in TypeScript without including all of its required fields, without creating a new interface or making all fields optional? Consider the following scenario: interface Test { one: string; two: string; } _.findWhe ...

Having trouble manipulating text or values of angular elements with Selenium and Python

https://i.stack.imgur.com/vZdo0.png I am facing an issue with a date input field that does not have a calendar or dropdown for selection. I tried using driver.find_element_by_id('dataInicio').send_keys(date_value) but it doesn't seem to work ...

Using the Ternary Operator in JavaScript to Dynamically Update HTML Elements with Angular

Is there a way to convert the code below into a ternary operator so that it can be used in an .HTML file? statusChange && statusChange === 'Employed' ? true : employmentStatus === 'Employed'; To clarify, I want to assign the re ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...

Is there a way to access the actionsObserver value from the Angular state?

When attempting to view state data using the code line this.store.select(selectUser), I am able to see the data as expected under actionsObserve. However, I am facing difficulty reading the data in actionsObserve with this line: this.store.select(selectUs ...

Show the alias of a type in Vscode Typescript instead of its definition

Here is some code that I am working with: type Opaque<T,U> = T & {_:U}; type EKey = Opaque<number,'EKey'>; type AKey = Opaque<EKey,'AKey'>; type PKey = Opaque<AKey,'PKey'>; let a = <PKey>1; ...

Typescript's implementation of AngularJs provider

After creating an Angularjs provider in typescript, I found myself wondering if there might be a more efficient way to achieve the same outcome. My current provider serves as an abstraction for a console logger, with the interface primarily designed to s ...

Sanity.io's selection of schema field types for efficient and convenient

Hey there, guys! I recently started using Sanity.io and I'm curious whether there's a way to enhance my code efficiency and reuse certain fields across different schemas. I had an idea that goes something like this: cars.ts: export default { ...

Styling your Angular project with CSS

I have a folder called about which contains a file named about.component.css . I want the background-color to be set to aqua only for the page about.component.html. When I try setting the background-color in about.component.css like this: body { backg ...

Switch the sidenav content dynamically in Angular 2 based on the current router state

Currently, I am in the process of developing a single page application using Angular 2. Within this project, I have implemented angular material mat-sidenav and mat-toolbar components. The toolbar includes a sidenav toggle button, as well as buttons that a ...

Is it possible to trigger a script tag based on certain conditions using a JavaScript function?

I'm currently working with Angular and have a requirement to trigger a third party script from a function located within another script tag. Here's an example scenario: Within the index.html file let displayOnHomepage = () => { if (win ...