1

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.

2
  • what exactly are you doing? you wan to add either bold or italic class to the <p> tag? Commented Jul 18, 2018 at 18:59
  • 1
    You don't use = in an object literal, you use :. So boldClass: this.isbold, for instance. Commented Jul 18, 2018 at 18:59

5 Answers 5

2

This is one way you can add dynamic classes

<p [class.boldClass]="isbold"
   [class.italicsClass]="isItalic">testing content </p>
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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>

Comments

1

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;
}

Demo

Comments

-1
[ngClass]="{'italicsClass':isItalic,'boldClass':isbold}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.