Difference Between Ng-Class and Ng-Style

What is the difference between ng-class and ng-style?

ng-style is used to interpolate javascript object into style attribute, not css class.

Following directive will be translated to style="color:red"

ng-style="{color: 'red'}"

And ng-class directive translates your object into class attribute.

Following will be translated to class="deleted" when isDeleted variable is true.

ng-class="{'deleted': isDeleted}"

Note:

There is one more use case for ng-style. If you want to interpolate something in style attribute, you should consider using ng-style. Otherwise, that would not work before Internet Explorer 11 as documentation suggests.

So, instead of using style:

style="width: {{progress}}"

Use ng-style:

ng-style="{'width':progress}"

What does putting [ngClass]=classand [ngStyle]=style do to an element when creating a component

The ngClass attribute allows a string (list of classes as space-delimited string), array of strings (list of classes) or object (with the keys as the classes and the values as whether the classes should be applied) to be specified.

However, the ngStyle attribute only allows an object (with the keys as the style names with an optional .<unit> prefix and the values which is an expression to be evaluated) to be specified.

For example:

<div [ngClass]="{'my-class': hasMyClass, 'another-class': true}"
[ngStyle]="{'display': isBlockDisplay ? 'block' : 'none', 'color': 'red'}">
<!-- Content here -->
</div>
<div [ngClass]="'my-class second-class'">
<!-- Even more content here -->
</div>
<div [ngClass]="['my-class, 'another-second-class']">
<!-- Wow, that's a lot of content! -->
</div>
<div [ngStyle]="{'max-width.em': maxWidthNumber}">
<p>Hello! This should be in a div with a max-width.</p>
</div>
export class MyComponent {
isBlockDisplay = true;
hasMyClass = false;
maxWidthNumber = 2;
}

The expected rendered HTML should be as follows:

<div class="another-class" style="display: block; color: red">
<!-- Content here -->
</div>
<div class="my-class second-class">
<!-- Even more content here -->
</div>
<div class="my-class another-second-class">
<!-- Wow, that's a lot of content! -->
</div>
<div style="max-width: 2em">
<p>Hello! This should be in a div with a max-width.</p>
</div>

AngularJS ng-class and ng-style working together

Try using !important in your class. This might fix your problem.

.selected{
background-color: red !important;
}

Inline style has higher precedence over css from class until !important is applied.

Cheers from CheezyCode

Difference between [ngClass] vs [class] binding

This is special Angular binding syntax

<div [class.extra-sparkle]="isDelightful">

This is part of the Angular compiler and you can't build a custom binding variant following this binding style. The only supported are [class.xxx]="...", [style.xxx]="...", and [attr.xxx]="..."

ngClass is a normal Angular directive like you can build it yourself

<div [ngClass]="{'extra-sparkle': isDelightful}">

ngClass is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example.

ngStyle and ngClass in Angular 2

In both cases, none should be 'none' with quotes. Because you should be assigning string value to the property display. none (without qoutes) will be evaluated at runtime and return undefined which is not an acceptable value of the css property display

//our root app component
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2 [ngStyle]="{'display': 'none'}">Hello {{name}}</h2>
<h2 [style.display]="'none'">Hello {{name}}</h2>
</div>
`,
directives: []
})
export class App {
constructor() {
this.name = 'Angular2'
}
}

Here is your plunker fixed

Update

This is from angular2 docs for NgClass directive:

The result of an expression evaluation is interpreted differently
depending on type of the expression evaluation result:

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

Array - all the CSS classes (Array elements) are added

Object -
each key corresponds to a CSS class name while values are interpreted
as expressions evaluating to Boolean. If a given expression evaluates
to true a corresponding CSS class is added - otherwise it is removed.

@Component({
selector: 'my-app',
providers: [],
styles:['.hide{display:none}',
'.border{border:3px solid blue}',
'.redBack{background-color:red}'
],
template: `
<div>
<h2 [ngStyle]="{'display': 'none'}">Hello {{name}}</h2>
<h2 [style.display]="'none'">Hello {{name}}</h2>
<h2 [ngClass]="'redBack'">Hello {{name}}</h2> // just normal string
<h2 [ngClass]="{'hide':hideFlag}">Hello {{name}}</h2> // will add class 'hide' if hideFlag is true
<h2 [ngClass]="mulClasses">Hello {{name}}</h2> // will add an array of classes ['border','redBack']
</div>
`,
directives: []
})
export class App {
hideFlag = false;
mulClasses = ['border','redBack']

constructor() {
this.name = 'Angular2'
}
}

here is the example in plunker

How to avoid using function in ngStyle or ngClass?

In general you can "map" your array and convert it in an array of objects,e.g.

const listValues=this.values.map(x=>{
return {
value:x,
style:this.getValueStyle(x)
}
})

And use

<td *ngFor="let item of listValues"
class="value">
<span [ngStyle]="item.style">{{item.value}}</span>
</td>

So, only call to getValueStyle so many times elements there are in your array "values"

Change color dynamically using ngClass or ngStyle in Angular

You can just bind to the HTML property instead:

<div (click)="divClicked = !divClicked">
<p [class.text-color]="divClicked">
some text...
</p>
</div>

in your component, create the class property to track the state of the click:

divClicked = false

Stackblitz

Is it possible to combine ng-class with ng-style

You could use ng-style instead of ng-class.

In this case:

<div class="card" ng-click="task.finished ||c.onWidget(task)" 
ng-class="{'c.finished': task.finished,
'c.overdue': !task.finished && task.isOverDue,
'c.pending': !task.finished && !task.isOverDue,
'c.optional': !task.finished && task.isOptional}">

The ng-class will add a class in your div like the string you defined, e.g:

If task.finished is true, then your div will look like this:

<div class="card c.finished" ng-click="task.finished ||c.onWidget(task)" 
ng-class="{'c.finished': task.finished,
'c.overdue': !task.finished && task.isOverDue,
'c.pending': !task.finished && !task.isOverDue,
'c.optional': !task.finished && task.isOptional}">

Note that the class added was "c.finished" and not the style you defined.

An idea would be to create a function in your controller to set the ng-style:

function myDivStyle(task){
if (task.finished) {
return c.finished;
} else if (!task.finished && task.isOverDue) {
return c.overdue;
} (...)
}

and then call this function in your div with ng-style:

<div class="card" ng-click="task.finished ||c.onWidget(task)" 
ng-style="myDivStyle(task)">

This should work like what you want.

Put a div in red using ngStyle or ngClass

You can do one of the following:

[ngClass]="this.account.placeAttribute == null ? 'red-bg' : 'blue-bg'"

OR

Make a method in your component like so:

getClassNames(){
if (this.account.placeAttribute == null){
let classes = {
"red-bg": true
}
return classes;
}
else{
let classes = {
"blue-bg": true
}

return classes;
}
}

Then in the template:

[ngClass]="getClassNames()"

Obviously red-bg and blue-bg are css classes that have background-color: red and background-color: blue respectively



Related Topics



Leave a reply



Submit