I'm currently working on Angular 9 and facing an issue while trying to create a reusable alert component. The problem lies in the alert-box selector where setting the alert type does not change its appearance. Instead, only plain text is displayed without any applied styles. Can anyone assist me in resolving this issue?
Example Usage:
<app-alert-box alertType="warning">
Hi, this is an alert message.
</app-alert-box>
My Implementation:
alert-box.component.html
<ng-container>
<div
[ngClass]="{
'alert-danger': alertType == 'danger',
'alert-info': alertType == 'info',
'alert-success': alertType == 'success',
'alert-warning': alertType == 'warning'
}"
class="alert"
role="alert"
>
<span class="alert-content" #alertContent>
<ng-content></ng-content>
</span>
<button (click)="alertClose()" *ngIf="closeButton" aria-label="Close">
X
</button>
</div>
</ng-container>
alert-box.component.scss
.alert {
padding: 20px;
color: white;
opacity: 1;
transition: opacity 0.6s;
margin-bottom: 15px;
.danger {
background-color: #f44336;
}
.success {
background-color: #4caf50;
}
.info {
background-color: #2196f3;
}
.warning {
background-color: #ff9800;
}
}
.closebtn {
margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
alert-box.component.ts
import { Component, OnInit, Input } from "@angular/core";
@Component({
selector: "app-alert-box",
templateUrl: "./alert-box.component.html",
styleUrls: ["./alert-box.component.scss"]
})
export class AlertBoxComponent implements OnInit {
@Input() alertType = "info";
@Input() closeButton = false;
@Input() autoClose = false;
@Input() autoCloseAfter = 5000;
alertOpen = true;
constructor() {}
ngOnInit(): void {
if (this.autoClose) {
const timer = setTimeout(() => {
this.alertClose();
clearTimeout(timer);
}, this.autoCloseAfter);
}
}
alertClose(): void {
this.alertOpen = false;
}
}