简体   繁体   中英

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 ?

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>

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM