Creating a class dynamically in Angular 2 Typescript based on a property value

How can I dynamically assign classes in HTML based on a property in Angular 2 without using jQuery or Bootstrap? I am trying to open a dropdown list.

Here is what I have:

<li
  class="dropdown mega-menu mega-menu-wide"

  //stuck at adding class of open if propertyval is admin
  >  
 <a #admin class="dropdown-toggle" (click)="toggle(admin)" >Administrative</a>
</li>

In my TypeScript file, I have:

export class ... {
  propertyval :null

   toggle(val){
    this.propertyval = null;
   }
  }

Now, I want to add the class "open" to the list if the value of propertyval is "admin", otherwise it should remain null.

How can I achieve this?

Answer №1

To dynamically add a class, you can utilize property binding.

<li
  class="dropdown mega-menu mega-menu-wide"
  [class.WhateverYouWant]="propertyval === 'admin'"
  //Need help adding the class 'open' if propertyval is admin
  >  
 <a #admin class="dropdown-toggle" (click)="toggle(admin)" >Administrative</a>
</li>

Answer №2

To apply styles dynamically, you can utilize the NgClass directive:

<li [ngClass]="{'class-open': open}">  
  <a #admin class="dropdown-toggle" (click)="open = !open;" >Administrative</a>
</li>

The class-open class modifies the dropdown list appearance based on the value of the open variable within your component. Ensure to initialize the open variable as either false or true, eliminating the need for a toggle() method.

Answer №3

Hey there! One way to incorporate dynamic styles is by using [ngClass].

<a #user class="dropdown-toggle" (click)="toggle(user)"  [ngClass]="{'styleClass': isUser }" >User Profile</a>

//style

.styleClass{
  font-weight: bold;
}

//.ts

       toggle(value){
        if(value != 'user') 
        {
            this.value = null;
            return isUser = false;
        }
        else {
            return isUser = true;
        }
}

Answer №4

Implement a method in your class that retrieves a boolean indicating the status of your property.

get isPropertyFilled(): boolean {
  return !isNullOrEmpty(this.propertyValue);
}

Next, include an ng-class directive in your HTML element.

<a [ng-class]="{ 'active': isPropertyFilled }"/>

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

Tips for adding a personalized close button to a Bootstrap modal

I need help with a Bootstrap modal in my project that has a close button positioned at the top right corner. I've used CSS to position the button, but it's not staying in one place consistently despite applying absolute positioning. I've tri ...

Determining the largest range possible in a sorted array of integers

I need help with a JavaScript implementation for the following challenge. Imagine we have a sorted array: [1,2,5,9,10,12,20,21,22,23,24,26,27] I want to find the length of the longest consecutive range that increments by 1 without duplicates. In the ...

Ways to reach state / methods outside of a React component

Implementing the strategy design pattern to dynamically change how mouse events are handled in a react component is my current task. Here's what my component looks like: class PathfindingVisualizer extends React.Component { constructor(props) { ...

"Utilize JavaScript to structure JSON, eliminate redundant entries, and calculate the total number

I'm feeling a bit disoriented, as I have this dataset in json format with timestamps and ids arranged like so: [{ "date":"2016-11-18 19:20:42","id_pa":"7" },{ "date":"2016-11-18 19:04:55","id_pa":"5" },{ "date":"2016-11-19 20:53:42","id_pa":"7" ...

What could be causing the increased build size of my Polymer2 compared to Angular5?

After reading multiple blogs, I decided to go with the polymer2 framework instead of angular. Some sources claimed that Polymer contributes less to the build size for production compared to angular2/5. To test this theory, I created two demo projects - on ...

Switch between displaying the HTML login and register forms by clicking a button

Currently, I am working on a website that requires users to either log in or register if they do not have an account. Below is the code I have developed for the login page: <span href="#" class="button" id="toggle-login">Log in</span> <di ...

Filtering a Table with Angular Material: Using multiple filters and filter values simultaneously

Looking to implement dual filters for a table of objects, one being text-based and the other checkbox-based. The text filter works fine, but struggling with the checkbox filter labeled "Level 1", "Level 2", etc. Ideally, when a checkbox is checked, it shou ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

Struggling to Personalize Kendo Calendar Month templates using Knockout Kendo JS Binding

I have made modifications to the Kendo Calendar Month Template Resource which can be found Here without utilizing knockout-kendo.js. The official Kendo Reference is available Here. The issue arises when I implement the following code in knockout-kendo.js ...

Using three.js to control the opacity and size of points

I have returned with question number two about points. My query this time revolves around changing the opacity from 0 to 1 and back within specific pixel distances from the emitter. var particleCount = 14, particles = new THREE.Geometry(), pMaterial = new ...

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...

Typescript's Type Specification

I am currently working with NextJs and Typescript and I am facing an issue. Whenever I include the "any" keyword in my code, it renders correctly. However, if I remove it, I encounter errors with post._id, post.title, and post.body. Challenge: Can someon ...

Discover the new method for establishing fixed column widths in the PrimeNG table now that the Autolayout property is no longer in use

Previously, I was able to customize the width of th elements in the primeng table template by using style="width: 25%". However, it seems that this feature is no longer supported and the documentation now mentions that autolayout is deprecated, resulting ...

What is the process for installing fontawesome using npm?

I encountered an error while attempting to install that looks like the following: $ npm install --save @fortawesome/fontawesome-free npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Admin\Desktop\package.json&a ...

Determine if a line intersects with a mesh in a three.js environment

Within the scene, there are several cylinders present. Upon user interaction with specific points, I am generating a line (THREE.Line) connecting those points. However, I am facing an issue with checking for intersections between the line and the cylinders ...

Tips for adjusting the size of grid tiles according to the dimensions of the window within a specific range

I am currently exploring how to replicate the effect found on this webpage: When the window size is adjusted, javascript dynamically resizes the grid tiles between 200 and 240px based on the optimal fit for the screen. Is there a ready-made JavaScript/jQ ...

Trigger an API request upon expanding a row in a mat-table

How can I trigger an API call to display more information about a selected row in the expansion when using Angular? I found an example at this link, but I'm not sure how to implement it. Any suggestions on how to accomplish this? ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

The issue of WithRouter Replace Component not functioning in React-Router-V6 has been encountered

As I upgrade react router to react router v6, I have encountered a problem with the withRouter method which is no longer supported. To address this issue, I have created a wrapper as a substitute. export const withRouter = Component => { const Wrappe ...

What is the best way to display SVGs from an API response using next/image or the <img> tag in Next.js?

I have a collection of SVGs being returned from an API response, which I am fetching inside the useEffect. The response structure is as follows: {svg1: 'https://remoteserver.com/assests/svg1.svg', ...and so on} (These SVGs are not static assets ...