I need help with dynamically displaying Bootstrap alert classes using Angular 2.
For example, if the MessageType
is 1, I want to show a Success message; for MessageType 2, an Error message should be displayed. See the code snippet below:
<div class="alert alert-success" role="alert">
Your data has been saved successfully.
</div>
<div class="alert alert-danger" role="alert">
Error occurred!!! Try again.
</div>
I attempted to implement dynamic classes like this, but it's not working as expected:
<div [ngClass]="['alert', 'alert-success': MessageType == 1, 'alert-danger' : MessageType == 2]" *ngIf="Message">
{{Message}}
</div>
add-todo.component.ts
export class TodoAddComponent {
Message: string;
MessageType: number;
AddItem(): void {
// do some processing
this.Message = "New Item has been added";
this.MessageType = 1;
}
}
I'm wondering how I can dynamically display the 'alert-success' or 'alert-danger' class in the HTML. Would it be better to handle it like this and then use the result in the HTML?
alertClass: string;
this.alertClass = 'alert-success'; // if successful
this.alertClass = 'alert-danger'; // if unsuccessful