0

How to apply CSS class condition to the below div element

i tried the below code but it is not working

  <div Class="{toolsMenuWidthSet==true?'dropdown-menu dropdown-menu-right dropdown-custom-width-links':'dropdown-menu dropdown-menu-right dropdown-custom-width-links-2'}"  aria-labelledby="dropdownMenuButton" id="appsDropdownPopup">

I want if toolsMenuWidthSet is true then apply the "dropdown-menu dropdown-menu-right dropdown-custom-width-links" else apply "dropdown-menu dropdown-menu-right dropdown-custom-width-links-2"

3 Answers3

2

Your syntax is wrong. There is a directive called ngClass in angular which you can use like this

 <div [ngClass]="toolsMenuWidthSet == true ? 'dropdown-menu dropdown-menu-right dropdown-custom-width-links' : 'dropdown-menu dropdown-menu-right dropdown-custom-width-links-2'"  aria-labelledby="dropdownMenuButton" id="appsDropdownPopup">

but if you don't want to use ngClass directive so you can also go with angular binding like this

<div class="{{toolsMenuWidthSet == true ? 'dropdown-menu dropdown-menu-right dropdown-custom-width-links' : 'dropdown-menu dropdown-menu-right dropdown-custom-width-links-2'}}"  aria-labelledby="dropdownMenuButton" id="appsDropdownPopup">
Fahad Hassan
  • 781
  • 10
  • 20
  • if we are using ngclass do we need to import something? As i tried this but it is not working for me –  Jan 29 '20 at 03:49
  • No, There was a typo in my answer. I updated my answer please see updated answer – Fahad Hassan Jan 29 '20 at 03:52
  • This is working but my css style is not getting applied as expected before all items were coming inside the div horizontal now it is coming vertical –  Jan 29 '20 at 04:10
  • if i put like class= 'dropdown-menu dropdown-menu-right dropdown-custom-width-links' it comes horizontal –  Jan 29 '20 at 04:11
  • This is because the last CSS is not getting applied –  Jan 29 '20 at 04:33
0

Use [ngClass]

 <div [ngClass]="{'dropdown-menu':toolsMenuWidthSet, 'dropdown-menu-right dropdown-custom-width-links':toolsMenuWidthSet, 'dropdown-menu': !toolsMenuWidthSet, 'dropdown-menu-right dropdown-custom-width-links-2':!toolsMenuWidthSet}"  aria-labelledby="dropdownMenuButton" id="appsDropdownPopup">

The CSS classes are updated as follows, depending on the type of the expression evaluation:

string - the CSS classes listed in the string (space delimited) are added,

Array - the CSS classes declared as Array elements are added,

Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

Doco:https://angular.io/api/common/NgClass

Mohamed Farouk
  • 1,089
  • 5
  • 10
0

Use this one, it's working fine.

<div class="dropdown-menu dropdown-menu-right" 
    [ngClass]="toolsMenuWidthSet==true ?
    ' dropdown-custom-width-links' : 
    ' dropdown-custom-width-links-2'"
    aria-labelledby="dropdownMenuButton" 
    id="appsDropdownPopup">