4

Hello I am trying to use a conditional class with an enum. I have used enums in html before with ngSwitchCase and have the same error that I'm getting now. When I would add a property called that enum and assign it to that enum it would work.

working example:

                    <ng-container *ngFor="let column of columns" [ngSwitch]="column.dataType">
                    <td *ngSwitchCase="DataType.Text">{{getPropertyValue(row,column.propertyName)}}</td>
                    <td *ngSwitchCase="DataType.Date">date</td>
                    <td *ngSwitchCase="DataType.Number">number</td>
                    <td *ngSwitchDefault>default</td>
                </ng-container>

ts

private DataType = DataType;

not working:

            <span *ngClass="(column.sortType === SortType.Ascending)? 'privilege-grid-sortasc': (column.sortType === SortType.Descending)?'privilege-grid-sortdesc':'privilege-grid-sortnone'"></span> 

I also have tried [ngClass] ="{'class-name': var === enum,...}"

ts

   private SortType = SortType;

error message:

Cannot read property 'Ascending' of undefined

2 Answers 2

4

I found a really good tutorial here : https://coryrylan.com/blog/angular-tips-template-binding-with-static-types

in summary the syntaxe is [ngClass] ="{'class-name': var === enum}":

@Component({
  selector: 'app-message',
  template: `
    <div class="message" [ngClass]="{
      'message--error': messageTypes.Error === type,
      'message--success': messageTypes.Success === type,
      'message--warning': messageTypes.Warning === type
    }">
      <ng-content></ng-content>
    </div>
  `
})
export class MessageComponent implements OnInit {
  @Input() type = MessageTypes.Default;
  private messageTypes = MessageTypes; //very important to declare here

  constructor() { }

  ngOnInit() { }
}
Sign up to request clarification or add additional context in comments.

Comments

3

I think your problem must lie somewhere else. I recreated your scenario using the [ngClass] binding with an enum and it works fine for me:

[ngClass] ="{'class-name': var === enum,...}"

Is your template in the second case on a separate .html file and not in the first case? I've had problems where a private variable on my component file can't be read by the template file.

2 Comments

it is in a separate html file.
the issue was that it is private.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.