Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngClass combine two expression types

Tags:

angular

Using ngClass I am trying to combine two expression types such that they are data bound and updated with changedetection like this

<div [ngClass]="[test.value | myClassPipe, {'anotherClass': test.isValid}]"></div>

Is the syntax wrong or is this not possible?

like image 369
doorman Avatar asked Nov 14 '16 08:11

doorman


People also ask

Can we add two classes in ngClass?

So far we've looked at adding just single classes, which is something the NgClass directive can also help us with as it supports multiple classes. Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class. class-name] on the same element.

Can we use ngIf and ngClass together?

Now you have learned the basics of Angular directives, including how to use ngIf, ngFor, ngClass, ngStyle, ngModel, and ngSwitch. You can combine them to create more complex user interfaces.

What type of directive is ngClass?

AngularJS ng-class Directive The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. If it is a string, it should contain one or more, space-separated class names.

Can we call method in ngClass?

You can use a method and a variable to construct the classes-string for the ngClass. In Template then you can use a method and a variable to construct the classes-string for the ngClass.


2 Answers

As per NgClass guide, A good way to apply NgClass is by binding it to a key:value control object. Each key of the object is a CSS class name; its value is true if the class should be added, false if it should be removed.

Consider a component method such as setClasses that manages the state of three CSS classes:

setClasses() {
  let classes =  {
    saveable: this.canSave,      // true
    modified: !this.isUnchanged, // false
    special: this.isSpecial,     // true
  };
  return classes;
}

Now we can add an NgClass property binding that calls setClasses and sets the element's classes accordingly:

<div [ngClass]="setClasses()">This div is saveable and special</div>
like image 168
ranakrunal9 Avatar answered Sep 22 '22 22:09

ranakrunal9


If the isValid property is being set in myClassPipe, try creating a function for ngClass.

-component.html

<div [ngClass]="{'anotherClass': checkIsValid(test)}"></div>

-component.ts

checkIsValid(test: any){  
     let converted = myClassPipe.transform(test); 
     if(converted.isValid) 
         return true; 
     else  
         return false; 
 }
like image 36
KarateJB Avatar answered Sep 20 '22 22:09

KarateJB