Search code examples
angularangular-ng-ifng-switch

Can a switch be used to set HTML element attributes in Angular?


I've got some nice logic in an HTML element to switch an attribute value between 2 options using if:

<igx-icon [name]="cell.value=='Modified' ? 'mode_edit' : 'file_upload'"></igx-icon>

Do I have a similar option if I had more than 2 cases? I know I could:

<div [ngSwitch]="cell.value">
    <igx-icon *ngSwitchCase="Modified" name="mode_edit></igx-icon>
    <igx-icon *ngSwitchCase="Uploaded" name="file_upload"></igx-icon>
    <igx-icon *ngSwitchCase="Third Case" name="thirdOption"></igx-icon>
</div>

but it's not as brief of direct as the first form. Is there a tool to be used to accomplish this directly on the name property?


Solution

  • You could set up a dictionary on your component to help with this:

    ExampleComponent {
        igxIconTypes = {
            'Modified': 'name',
            'Uploaded': 'file_upload',
            ...
        };
    }
    

    You could then use it like this in your template:

    <igx-icon [name]="igxIconTypes[cell.value]"></igx-icon>
    

    You could then set up a default case (in which there wasn't a match) by using the || operator like this:

    <igx-icon [name]="igxIconTypes[cell.value] || 'default_icon'"></igx-icon>