Samuel
Samuel

Reputation: 1406

Conditional class values using ngClass - Angular

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 ?

Upvotes: 0

Views: 4792

Answers (4)

Onur Topal
Onur Topal

Reputation: 3061

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

Upvotes: 1

tmsbrndz
tmsbrndz

Reputation: 1347

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>

Upvotes: 2

Bertramp
Bertramp

Reputation: 385

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>

Upvotes: 0

Andreas Turku
Andreas Turku

Reputation: 413

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' } ]`
};

Upvotes: 0

Related Questions