I have a set of objects stored in my component. I need to dynamically apply different classes based on the value of the ErrorLevel property within each object. If an object has ErrorLevel equal to 1, I want to assign the following classes to various elements:
class-red
class-container-red
class-message-red
If the ErrorLevel is not equal to 1, I would like to assign the following classes to the elements instead:
class-yellow
class-container-yellow
class-message-yellow
Is there a more efficient way to achieve this using Angular or CSS (or SASS) without having separate methods for each individual class?
Here is an example code snippet showcasing what I currently have:
<html>
<body>
<div *ngFor="let obj of myObjects">
<h1 [ngClass]="getCssClass(obj.ErrorLevel)"></h1>
<p [ngClass]="getCssClass2(obj.ErrorLevel)"></p>
<div [ngClass]="getCssClass3(obj.ErrorLevel)"></div>
</div>
</body>
</html>
export interface MyObject {
Id: number;
ErrorLevel: number;
}
@Component({
selector: 'my',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
@Input() myObjects: MyObject[];
constructor() { }
ngOnInit() {
}
getCssClass(errrorLevel) {
if(errrorLevel === 1) {
return "class-red";
} else {
return "class-yellow";
}
}
getCssClass2(errorLevel) {
if(errrorLevel === 1) {
return "class-container-red";
} else {
return "class-container-yellow";
}
}
getCssClass3(errorLevel) {
if(errrorLevel === 1) {
return "class-message-red";
} else {
return "class-message-yellow";
}
}
}