Is there a way to transfer ngClass logic from the template to the TypeScript file in Angular?

I am implementing dropdown filters for user selection in my Angular application. The logic for adding classes with ngClass is present in the template:

<div [ngClass]="i > 2 && 'array-design'">

How can I transfer this logic to the controller for better unit testing capabilities?

<ng-container *ngIf="searchFilters.length > 0; else loading">
        <div class="filter-items" *ngFor="let filter of searchFilters; index as i">
            <div [ngClass]="i > 2 && 'array-design'">
                <app-multi-select [items]="filter.navigators" [title]="filter.name"></app-multi-select>
            </div>
        </div>
    </ng-container>

.scss

.cross-reactivity, .array-design{
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 5px;
}

Answer №1

One way to incorporate the conditional statement is by creating a separate function to handle it, and then using the function's return value within your HTML code.


Here is an example:

[ngClass]="applyFilter(i)"

In your .ts file:

const applyFilter = (i) => i > 2 ? 'array-design' : '';

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

Issues with rendering in Next.jsORErrors encountered during rendering

Encountering errors while attempting to build my page using "Yarn Build" Automatically optimizing pages ... Error occurred prerendering page "/design/des". More details: https://err.sh/next.js/prerender-error: Error: Cannot find module './des.md&apos ...

The JSON object is coming back as null

I need some clarification on why I am getting an "undefined" alert. Any assistance you can offer would be greatly appreciated as this problem is holding up progress on a crucial project. JavaScript $.getJSON("item-data.json", function(results) { ...

Are there any publicly accessible Content Delivery Networks that offer hosting for JSON2?

Everyone knows that popular tech giants like Google and Microsoft provide hosting for various javascript libraries on their CDNs (content distribution networks). However, one library missing from their collection is JSON2.js. Although I could upload JSON2 ...

Discontinuing the fieldset tab interface feature from a Dexterity content type

I am looking to modify a condition to prevent the loading of certain javascript code when inserting an object of my content type. The current condition works only when editing the object: <?xml version="1.0"?> <object name="portal_javascripts"> ...

Scroll to make the div slide in from the bottom

I'm trying to achieve a similar effect like the one shown in this website (you need to scroll down a bit to see the divs sliding in). Although I'm not very proficient in JS, I was able to create a code that makes the divs fade in from 0 opacity ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...

Is it possible to conceal dom elements within an ng-template?

Utilizing ng-bootstrap, I am creating a Popover with HTML and bindings. However, the ng-template keeps getting recreated every time I click the button, causing a delay in the initialization of my component. Is there a way to hide the ng-template instead? ...

Tips for transforming a JSON Array of Objects into an Observable Array within an Angular framework

I'm working with Angular and calling a REST API that returns data in JSON Array of Objects like the example shown in this image: https://i.stack.imgur.com/Rz19k.png However, I'm having trouble converting it to my model class array. Can you provi ...

Experiencing issues with the redirect button on the navigation bar of my website

Video: https://youtu.be/aOtayR8LOuc It is essential that when I click a button on my navigation bar, it will navigate to the correct page. However, since the same nav bar is present on each page, it sometimes tries to redirect to the current page multiple ...

What could be causing TypeScript to display errors in unexpected locations while inferring inner types?

I encountered a rather intricate issue that's challenging to sum up in a brief title, my apologies for that. I devised a function that accepts a generic params type and returns a result type constructed from the params type. It utilizes string literal ...

Setting a data type for information retrieved from an Angular HTTP request - A Step-by-Step Guide

Here is the code I use to fetch data: login() { const url = api + 'login'; this.http.post(url, this.userModel) .subscribe( data => { localStorage.token = data.token; this.router.navigate(['/home&a ...

Tips for showing images with the full path URL retrieved from JSON using AngularJS

I am currently working on a project that involves displaying images from a JSON file. The URLs of these images are stored in the JSON file. Currently, my code is only outputting the URLs themselves, which is expected. However, I am looking for a way to act ...

Leveraging an intersection type that encompasses a portion of the union

Question: I am currently facing an issue with my function prop that accepts a parameter of type TypeA | TypeB. The problem arises when I try to pass in a function that takes a parameter of type Type C & Type D, where the intersection should include al ...

Is the setInterval function in JavaScript only active when the browser is not being used?

I am looking for a way to ensure proper logout when the browser is inactive using the setInterval() function. Currently, setInterval stops counting when the browser is active, but resumes counting when the browser is idle. Is there a way to make setInterv ...

Best practices for customizing v-calender in vue.js

I'm struggling with styling my calendar using the v-calendar Vue plugin. I want to customize the background of the calendar, but my code doesn't seem to be working. Can someone please help me out? Thank you in advance. HTML <v-calendar ...

transferring information to d3.js

I have a json object structured in the following way { "tweet":[ {"text": "hello world"}, {"text": "hello world"} ] } When I check the console output of "data" in my code below, it shows me an Object tweet: Array[131]. However, when I l ...

Angular's CanActivate feature fails to navigate to a new route upon calling the refresh token API, even if it returns true

I have been implementing route guard and token interceptor in an Angular 6 project. Within the route-guard's canActivate method, there is an async function that verifies whether the access token has expired: If it has expired, the system checks i ...

Exploring React JS Subdomains

I have been developing a MERN application that needs to support dynamic subdomains for each company, like companyname.localhost. In order to make this work, I made an adjustment in my .env file with the line: DANGEROUSLY_DISABLE_HOST_CHECK=true After a us ...

What is the reason behind Q.js promises becoming asynchronous once they have been resolved?

Upon encountering the following code snippet: var deferred = Q.defer(); deferred.resolve(); var a = deferred.promise.then(function() { console.log(1); }); console.log(2); I am puzzled as to why I am seeing 2, then 1 in the console. Although I ...

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...