1

I am looping through a list and displaying buttons.

Within my loop I have job.hasJob. If this is set to 1 then I would like to add a class to the button. The name of the class should be job-block- plus the value of job.hasJobDetails.statusColour

For example, if job.hasJobDetails.statusColour is red then the class name is job-block-red.

If I hard code in the class then it works:

<button ion-button color="dark" [ngClass]="{ 'job-block-red' : job.hasJob == 1}" (click)="changeStatus(job.statuses)" outline>{{ job.jobName }}</button>                

But if I try this then I get an error:

<button ion-button color="dark" [ngClass]="{ 'job-block-' + job.hasJobDetails.statusColour : job.hasJob == 1}" (click)="changeStatus(job.statuses)" outline>{{ job.jobName }}</button>              

Parser Error: Missing expected : at column 16 in [{ 'job-block-' + job.hasJobDetails.statusColour : job.hasJob == 1}] in BedJobsPage@62:39 ("

1 Answer 1

6

I don't think you can use the object notation for ngClass with dynamic property names. Try something like this instead:

[ngClass]="job.hasJob == 1 ? 'job-block-' + job.hasJobDetails.statusColour ? null"

or build your class object in typescript:

getJobClasses(job) {
   return {
       ['job-block-' + job.hasJobDetails.statusColour] : job.hasJob == 1
   }
}

[ngClass]='getJobClasses(job)'
Sign up to request clarification or add additional context in comments.

3 Comments

I went for option 2 and that worked a treat. Thank you.
Actually the 2nd example is a very bad idea. The Method returns a new object every time it's called and it's called every time change detection runs which can be quite often. You should rather cache the object in a field and only return a new instance when it actually was changed. ngClass also recognizes changes within an object, therefore it's not necessary to return a new instance at all.
With the first one I got an error "NgClass can only toggle CSS classes expressed as strings, got null" but I fixed it by using '' instead.

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.