0

I want to apply multiple class but there is some difference here compared to other questions of Stackoverflow.

I have to dynamically assign icon class and also 'not-selected'

component.ts

list = [ { name: 'Name1', icon: 'icon_1' }, { name: 'Name2', icon: 'icon_2' } ]
<div *ngFor="let data of list" 
    [ngClass]="{ 'some_icon' : true , 'not-selected': selectedOperation?.name !== operation.name }"> 
    {{data.name}} 
</div>

I can see some_icon but what I need is dynamically assign data.icon too. something like:

<div *ngFor="let data of list" 
    [ngClass]="{ data.icon , 'not-selected': selectedVal?.name !== data.name }"> 
    {{data.name}} 
</div>

but this one is not the correct syntax. What am I missing ?

0

4 Answers 4

2

You can try with [class] input.

<div *ngFor="let data of list" [class]="data.icon"
    [ngClass]="{'not-selected': selectedVal?.name !== data.name }"> 
    {{data.name}} 
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

while using [ngClass] you have 3 options, one giving the object that way the keys will be the class name if the value returns true (truthy). the others are regular string and list of arrays but you cannot use a combination of them. For your case, you can use a combination of class and [ngClass] this way you can also use static class names in the HTML as well.

class="{{iconName}} static-class-name" [ngClass]="{'redClass': useRedClass}"

you must define your data similar to the below one.

export class AppComponent {
  title = "CodeSandbox";
  iconName = 'icon1';
  useRedClass = true;
}

Comments

0

When the dynamic event happens that will trigger your icons to be changed, assign your list again

private myDynamicChangeHandler = () => {
    this.list = [ { name: 'Name1', icon: this.useIcon1 ? 'icon_1' : 'icon_2' }, { name: 'Name2', icon: this.useIcon1 ? 'icon_1' : 'icon_2' } ]`
};

1 Comment

I can have n number of icon with a list which has length n
0

I have had success adding dynamic icon classes to the 'normal' class property string with string interpolation and also with pipes. Maybe it works for you too. Remember to add spaces between the class names

<div *ngFor="let data of list" 
    [class]="{{data.icon}} + ' ' +'otherDivClass redIconColorClass'"> 
    {{data.name}} 
</div>

1 Comment

probably He cant deal with conditional class here.

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.