I am currently developing a custom alert box component in Angular 9. While trying to modify the alert type, I have encountered an issue where the appropriate CSS class is not being assigned

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;
  }
}

Answer №1

Your classes are named alert-danger, alert-success,... but your CSS is only referencing alert and success. Update your CSS to:

.alert {
  padding: 20px;
  color: white;
  opacity: 1;
  transition: opacity 0.6s;
  margin-bottom: 15px;

  &.alert-danger {
    background-color: #f44336;
  }
  &.alert-success {
    background-color: #4caf50;
  }
 &.alert-info {
    background-color: #2196f3;
  }
  &.alert-warning {
    background-color: #ff9800;
  }
}

Take a look at the Stackblitz example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate written output using a collection of C# class titles on a typewriter

I need help finding a setup or template file for creating TypeScript files based on a group of C# classes with Typewriter. Here's an example of what I'm looking for: $Classes(['myclass1','myclass2','myclass3'])[ ...

Establishing a standard value for a class that can be injected

Here is my desired approach: @Injectable() export class MyInjectableClass { constructor(timeout: number = 0) { } } The goal is to have the timeout set to 0 when it's injected, but allow the calling code to specify a different value when constr ...

Setting view encapsulation globally in Angular2 allows you to define a consistent

I have made the decision to globally set ViewEncapsulation.None for all the components in my project. Instead of having to manually set it in each component's decorator, how can I apply this setting project-wide? Note: For reference, my dependencies ...

Modifying the rotation speed of an 'fa-icon' element in Angular using Font Awesome

In my component, I am working with the following HTML template: ` <fa-icon class="basketball" [icon]="['fas','basketball-ball']" size="2x" [spin]="true"></fa-icon> ` This code generates the following HTML DOM element: ` & ...

Align your content perfectly on a full-screen slick slider

Attempting to center content over a full-screen slick slider from kenwheeler.github.io/slick/, I used a flexbox but the content remains at the edge of the viewport. It seems like an issue with the position tag in the slick CSS, but I can't figure out ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Move the scroll event binding from the parent element to the child element

I'm working on an HTML page with the following structure: <div class="parent"> <div class="child1"> <div class="child2"> </div> </div> </div> Currently, I have a scr ...

What is causing my div to transition repeatedly from the bottom to the top instead of the center position?

Currently, I am using React and Tailwind CSS and facing an issue with the transition property. My goal is to have a div grow in width and height from the center until it covers the entire viewport when a specific state variable becomes true. The content in ...

Primeng - Concealed dropdown values within a scrollable table header

Recently, I integrated Primeng p-table with a filter and frozen column feature (with one column being fixed while the others are movable). However, I encountered an issue with the select dropdown in the header. When I try to open the dropdown, the values a ...

Is there a way to stop a click event on an Angular component's host from triggering?

Currently, I'm developing an Angular component that adds extra functionality to a native <button> element. In this component, I would like to mimic the behavior where buttons do not trigger a click event if they are disabled. For instance: < ...

CSS Navigation Bar Fails to Function Properly on Mobile Devices

Check out the plunkr I have created by visiting: http://plnkr.co/edit/gqtFoQ4x2ONnn1BfRmI9?p=preview The menu on this plunkr functions correctly on a desktop or laptop, but it doesn't display properly on a mobile device. I suspect that the issue may ...

How to exit a dialog in an Angular TypeScript component with precision

Hey there, I'm attempting to close a dialog from the component by specifying the path in .angular-cli.json and calling the function. However, it seems that despite my efforts, the dialog isn't closing and the redirection isn't happening. He ...

Designed radio buttons failing to activate when focused using a keyboard

I'm facing an issue with radio input buttons that I've dynamically added to a div using jQuery. They function properly when clicked with a mouse, but do not get activated when using the keyboard tab-focus state. NOTE: To style the radio buttons ...

HTML and CSS - Aligning text and managing scrollbar visibility

I am currently diving into the world of coding and embarking on the journey of crafting a website for my father. This project not only helps me gain valuable experience but also builds up my portfolio. Utilizing unsemantic and normalize frameworks, I enco ...

Unable to invoke Kendo JavaScript

I'm facing an issue with my source code where I am trying to call kendo.all.min.js. Everything works fine when I call kendo.common.min.css and kendo.default.min.css, but as soon as I try to call kendo.all.min.js, I encounter the following error: http ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Is there a way to eliminate the gap beneath each row of my Tic-Tac-Toe grid in Next.js with CSS styling?

What could be causing the space under every row in my CSS? I am currently developing a tic-tac-toe application using Next.js to enhance my skills. However, I have encountered an issue with the CSS where there appears to be a small space underneath each bo ...

Setting the root directory and output directory can be a bit tricky when dealing with source code scattered across multiple folders. Here's

Utilizing TypeScript in my Node.js project, I previously had a directory structure that looked like this: node_modules src -Models -Routes -Middlewares -Controllers -index.ts package.json tsconfig.json In ...

Is it possible to assign a variable in typescript using the interface as its type?

Here's the snippet of code I have written interface apiResult { Token: string; Result: any; } const result: apiResult = payload.Result; I am wondering about the significance of this code. Is it possible to assign a type from an interface to ...

What are the steps to combine two collections using rxjs?

I need to combine two collections (tokens and trends) based on their IDs, where each item in the result should include data from both collections. This means that the ID of an item in the trends collection matches the ID of the corresponding item in the to ...