Reputation: 53
Here I want to add CSS classes dynamically to the element using ngClass directive in angular.js.
<p [ngClass]="addClasses()">testing content</p>
and below is my ts code:
isbold: boolean = false;
isItalic: boolean = true;
addClasses() {
let classes = {
boldClass: this.isbold,
italicsClass: this.isItalic
};
return classes;
}
boldClass and italicsClass are two classes in my css file, these classes should apply depending on the value in the corresponding boolean variables. But I'm getting the error as Can not find name for both boldClass and italicsClass. Any help appreciated.
Upvotes: 1
Views: 18552
Reputation: 14600
ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
isbold: boolean = false;
isItalic: boolean = true;
addClasses() {
let classes = {
boldClass: this.isbold,
italicsClass: this.isItalic
};
return classes;
}
}
template:
<p [ngClass]="addClasses()">testing content </p>
css:
.boldClass {
font-weight: bold;
}
.italicsClass {
font-style: italic;
}
Upvotes: 1
Reputation: 189
Try using Angular's Renderer2
@ViewChild('el') element: ElementRef
constructor(private renderer: Renderer2) {
}
addClasses(classes: Array<string>){
classes.forEach(class => this.renderer.addClass(this.element.nativeElement, 'someClass'))
}
<p #el>testing content </p>
Upvotes: 1
Reputation: 13784
The issue is with your JSON, when you declare a JSON, the properties of it shouldn't be with the "=", try to use something like:
addClasses(){
let classes={
boldClass: this.isbold,
italicsClass: this.isItalic
};
return classes;
}
There was a pending "," after this.isbold, and also, you had this.Italic, and it should be this.isItalic.
Upvotes: 2
Reputation: 1004
This is one way you can add dynamic classes
<p [class.boldClass]="isbold"
[class.italicsClass]="isItalic">testing content </p>
Upvotes: 2