0

I am taking in JSON data and generating a material list from them with mat-list using the *ngFor directive.

I have also researched and found that using [NgClass] = "{'CssClassName': condition}" enables me to apply different CSS classes to each list entry depending on any value of my choosing within the data itself.

However... I am changing the background style of each entry depending on their ID number, and I have 10 IDs making this NgClass section within the HTML rather long and difficult to read as you are not able to split this onto different lines...

You can see below how long the actual line of code is - of course the text does wrap in my editor, but it still look horrendous - Full code example

<mat-chip class="list-item" [ngClass] = "{'one':r.id === 1, 'two':r.id === 2,'three':r.id === 3, 'four':r.id === 4,'five':r.id === 5, 'six':r.id === 6,'seven':r.id === 7, 'eight':r.id === 8, 'nine':r.id === 9, 'ten':r.id === 10}">

Is there a more elegant way of achieving the same outcome that I am unaware of?

2 Answers 2

2

If your class are named "class1","class2","class3"... (not "one", "two","three"..) you can use

<mat-chip class="list-item" [ngClass]="'class'+r.id">
Sign up to request clarification or add additional context in comments.

1 Comment

oh groovy! I didn't realise this could work. So much simpler than having to refactor all of my code XD
1

You could make a function for that !

[ngClass]="createClassesObject(r)"

In your TS

createClassesObject(r: any) {
  return {
    one: r.id === 1,
    two: r.id === 2,
    // You get the point
  };
}

EDIT You can even shorten the function (proof of work) :

indexes = ['zero', 'one', 'two', 'three']; // etc.

createClassesObject(r: any) {
  return this.indexes.reduce((p, n) => {
    if (r.id === this.indexes.indexOf(n)) { p[n] = true; }
    return p;
  }, {})
}

2 Comments

Thanks for explaining! Makes a lot of technical sense, although I am going to accept @Eliseo's answer above, don't think I don't like or don't appreciate yours! :-)
No problem, I too upvoted his answer. It's much cleaner and easier !

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.