The ngclass is not working as expected in angular 6

2.2k Views Asked by At

I am trying to change the value of [ngclass] field based on the values present in array but it is not working as expected. The html code is as below:

<ul>
                  <li [ngClass]="{active: uniqueIds == corporate }">
                    <a href="/questionnaire/"> 
                      <span class="icons">
                        <i class="fas fa-users"></i>
                    </span> 
                      <span>Corporate</span> 
                    </a>
                  </li>
                  <li id="dispatchLocations" [ngClass]="{active: uniqueIds == dispatchLocations}">
                    <a href="/questionnaire/three/"> 
                      <span class="icons">
                        <i class="fas fa-map-marked-alt"></i>
                    </span> 
                      <span>Dispatch locations  </span> 
                    </a>
                  </li>
</ul>

In above code uniqueIds is an array which is populated as below:

private message = [];
private questionLiId: any;
liIds: Array<any>;
  public uniqueIds : Array<any>;
 constructor(private sharedMessage: ShareMessageService) {
    this.liIds =[];
    this.uniqueIds=[];
  }
ngOnInit() {
    this.sharedMessage.shareMessage$.subscribe((data) => {
      this.message = data;
      this.questionLiId=this.message[4];
      setTimeout(()=>{
        this.liIds.push(this.questionLiId);
        this.uniqueIds =Array.from(new Set(this.liIds));
        console.log("Unique Li Ids =>"+this.uniqueIds);
      },0)
    })
  }

When I see in the console unique li ids is printed as below:

Unique Li Ids =>corporate,dispatchLocations

When i inspect html code the following is displayed:

<li _ngcontent-c4="" ng-reflect-ng-class="[object Object]">Corporate</li>

Can anyone help me to resolve this in angular 6? I am not being able to change the value of ngclass. I have tried the following solutions so far:

[ngClass]="{active: uniqueIds.indexOf() == corporate }"

[ngClass]="{active: uniqueIds.contains == corporate }"

[ngClass]="{active: uniqueIds.container == corporate }"

[ngClass]="{active: uniqueIds.value == corporate }"

[ngClass]="{active: uniqueIds == corporate }"

[ngClass]="{uniqueIds == corporate ? 'active':'inactive }"

But none of the above worked for me.

3

There are 3 best solutions below

0
On

corporate should be a string:

[ngClass]="{'active': uniqueIds.indexOf('corporate') !== -1 }"
0
On

try to call method from the controller

[ngClass]="getLiClass(uniqueIds, 'corporate')"

in the controller. add that function:

   getLiClass(uniqueIds, testValue) {
     return uniqueIds.contains(testValue) ? 'active':'inactive';
   }
0
On

try this .. because uniqueIds is an Array, you need search its index.I thought that was the simpler way

 <li [ngClass]="{'active': uniqueIds.indexOf('corporate')!= -1 }">

for more info follow this link https://angular.io/api/common/NgClass#ngclass