Assigning a class based on a property value in angular2 typescript

时间:2018-01-15 18:08:00

标签: javascript angular typescript typescript2.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 个答案:

答案 0 :(得分:2)

您可以使用属性绑定动态添加类。

<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>

答案 1 :(得分:2)

您可以使用NgClass指令:

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

class-open - 是影响下拉列表的类。 open是您在组件中最初设置为false或true的变量,因此不需要toggle()方法。

答案 2 :(得分:1)

您可以使用[ngClass]添加动态样式。

NHibernate

//风格

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

//。ts

.dynStyle{
  color:green;
}

答案 3 :(得分:0)

在你的类上创建一个getter,为你的属性状态返回boolean。

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

然后将ng-class指令添加到元素

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