1

I have 20+ elements, which all should use the same class (animate.css)

It is super annoying to change all classes if I want to edit the animation, so I saved the animation class in my service in a variable:

animClassSecond = "animate__animated animate__bounceInUp";

But I cant figure out how to add it to [ngClass], this does not work:

[ngClass]="{'select_elem':true, 'btn_2':true, 'dataService.animClassSecond':true}"
[ngClass]="{'select_elem':true, 'btn_2':true, 'this.dataService.animClassSecond':true}"
[ngClass]="{'select_elem':true, 'btn_2':true, this.dataService.animClassSecond:true}"
[ngClass]="{'select_elem':true, 'btn_2':true, dataService.animClassSecond:true}"

Its either a template error or it does not resolve to the variable. Any ideas?

P.S.: Adding a second [ngClass] attribute also does not work, because the first one is ignored.

2 Answers 2

6

is:

[ngClass]="dataService.animClassSecond"

But remember that you need declare the service public in the constructor

constructor(public dataService:DataService){}

NOTE you can use class and [ngClass] in the same tag:

class="select_elem btn_2" [ngClass]="dataService.animClassSecond"
Sign up to request clarification or add additional context in comments.

Comments

0

This is probably not achievable in the template since the Angular template language is quite limited.

Just move the logic of ngClass object into your component.ts. There you can use all TypeScript's power

ngOnInit() {
  this.ngClassObj = { [dataService.animClassSecond]: true };
}

or if you need it to be dynamic (use this one carefully because it might become a performance issue)

get ngClassObj() {
  return { [dataService.animClassSecond]: true };
}

and then

[ngClass]="ngClassObj"

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.