0

I would like to assign a classes on html based on a property in angular2. That is am trying top open a dropdownlist without use of jquery and bootstrap

So 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 ts i have

export class ... {
  propertyval :null


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

So now i would like to assign class of open to the list if the value of propertyval is admin else it should be null

How do i go about this

4 Answers 4

2

You can use property binding to add the class dynamically.

<li
  class="dropdown mega-menu mega-menu-wide"
  [class.WhateverYouWant]="propertyval === 'admin'"
  //stuck at adding class of open if propertyval is admin
  >  
 <a #admin class="dropdown-toggle" (click)="toggle(admin)" >Administrative</a>
</li>
Sign up to request clarification or add additional context in comments.

Comments

2

You can use NgClass directive:

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

class-open - is your class that affects dropdown list. open is your variable that you set initially to false or true in your component, so no need for toggle() method.

1 Comment

the class should be assigned to li not a tag
1

Hi you can use [ngClass] for adding dynamic styles.

<a #admin class="dropdown-toggle" (click)="toggle(admin)"  [ngClass]="{'dynStyle': isAdmin }" >Administrative</a>

//style

.dynStyle{
  color:green;
}

//.ts

       toggle(val){
        if(val!='admin') 
        {
            this.propertyval = null;
          return isAdmin=false
           }
         else

    {
    return isAdmin=true;
    }
}

Comments

0

Create a getter on your class, returning boolean for the state of your property.

get propertyHasValue(): boolean {
  return !isNullOrUndefined(this.propertyval);
}

Then add an ng-class directive to your element

<a [ng-class]="{ 'open': propertyHasValue }"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.