Professional Documents
Culture Documents
element
www.webcodegeeks.com /javascript/angular-js/learning-angular-2-conditionally-add-styleselement/
+Juri Strumpflohner
Here were going through a couple of ways to conditionally apply some styles to a DOM element in
Angular 2.
Adding a class
Similarly as we did with the background-color above, we can add a class, using the following notation:
[class.nameOfClass]="someCondition".
//our root app component
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<div [class.my-class]="isClassVisible">
I am a div that wants to be styled
</div>
<button (click)="isClassVisible = !isClassVisible;">Toggle
style</button>
</div>
`,
styles: [
`
.my-class {
background-color: yellow;
}
`
]
directives: []
})
export class App {
isClassVisible: false;
constructor() {
}
}
@Component({
selector: 'my-app',
providers: [],
...
directives:
[NgClass]
})
Then we can use it just as we did in Angular 1. Heres the full code example.
//our root app component
import {Component} from 'angular2/core';
import {NgClass} from 'angular2/common';
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<div [ngClass]="{'my-class': isClassVisible }">
I am a div that wants to be styled
</div>
<button (click)="isClassVisible = !isClassVisible;">Toggle
style</button>
</div>
`,
styles: [
`
.my-class {
background-color: yellow;
}
`
]
directives: [NgClass]
})
export class App {
isClassVisible: false;
constructor() {
}
}
Conclusion
So in this article you learned about three possibilities to style your DOM elements from within Angular
2. You got to see
directly binding with [style.background-color]
adding a class [class.my-class]
using NgClass [ngClass]
by directly accessing the native DOM element
You even quickly saw how to create a Directive and how to embed styles within a Component .
Reference: Learning Angular 2: Conditionally add styles to an element from our WCG partner Juri
Strumpflohner at the Juri Strumpflohners TechBlog blog.