Displaying Bootstrap classes dynamically within an Angular 2 application

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

Answer №1

Another option is to connect directly to the necessary alert-x class using class binding:

<div *ngIf="Message"
      class="alert"
     [class.alert-success]="MessageType == 1"
     [class.alert-danger]="MessageType == 2">
   {{Message}}
</div>

Answer №2

It is recommended to pass an object to the [ngClass] directive instead of using an array, as your current setup involves an invalid array-object combination.

An array should simply specify which classes you want to apply, while an object can be used to define conditions for displaying specific classes.

<div [ngClass]="{alert: true, 'alert-success': MessageType == 1, 'alert-danger': MessageType == 2 }" *ngIf="Message">
    {{Message}}
</div>

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

Issue with ngModel being undefined after data has finished loading in Ionic 3

As a newcomer to Angular 4, I've been struggling to find a solution for a seemingly simple issue related to an Ionic app. Whenever a user logs in, the entire user object is saved to localStorage. Despite trying various plugins, I settled on a straight ...

Necessary to retrieve and parse a remote file via its URL, converting the data into JSON format

For my current project, I am required to retrieve a CSV file from a URL like this link and convert it to JSON. I am familiar with reading local files using an input tag, but need assistance with this task. ...

Error Found in Infinite Scroll Functionality in Ionic 2

I have been attempting to incorporate infinite scrolling into my application, but I keep encountering an error that says Property "then" does not exist on type "void". This issue appears in both my text editor and the console when the page reaches the bott ...

What could be the reason for Angular Router to receive query parameters twice?

I have an application that consists of two pages with lists. On Page A, clicking on an item will display the corresponding detail page. The detail page contains a list of sub-items, and clicking on any sub-item navigates to Page B with the sub-item's ...

What is the best way to update queryParams without activating subscribe functions?

Hello, I am currently in the process of developing an angular app with multiple routes. When navigating to a specific page, the queryParams trigger the subscribe function. While on the page, I need to be able to change the queryParams without triggering ...

Guidance on extracting values from an array based on the latest month in Angular

I have a list of data: var dataList = [{ "date": "2022-09-08T04:00:00.000Z", "value": "1.70", }, { "date": "2022-08-24T04:00:00.000Z", "value": "1.20", }, { "date": "2022-08-02T04:00:00.000Z", "value": "0.03", }, { ...

What benefits could be gained from enabling the compiler option "declaration" in a TypeScript project?

I am currently working on a TypeScript project and contemplating the possibility of publishing it as an NPM package in the future. Currently, I have the "declaration": true setting in my tsconfig.json, which is causing some issues that are irrelevant to t ...

In the past, my code would run smoothly without any issues, but now I am encountering a runtime error even though the code comp

Recently, I started learning TypeScript and encountered an issue while working with Classes. My code was functioning properly before but now it's displaying a runtime error. ...

Angular Route Authorities is a powerful tool for managing permissions

In my routes, I have a specific path: {path: 'Demands/:id', component: EditDemandesComponent}. This path allows me to edit demands. However, I've noticed that if the ID does not belong to one of my demands, I am still able to access the path ...

Utilizing NPM Workspaces to efficiently distribute TypeScript definition files (`*.d.ts`) across multiple workspaces

In my TypeScript monorepo utilizing NPM Workspaces, I have two packages: A and B. Package B requires type definitions from package A. To accomplish this, I included a reference to A's definition file in the tsconfig.json of package B. However, somet ...

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...

What is the best way to disable a submit button based on form validity in Angular 4 with ng-content?

Include a form component that consists of an email field, password field, and submit button passed through ng-content. This allows the login form to display a 'Login' button and the register form to display a 'Register' button. Here is ...

"Utilizing Primeng's dynamic functionality to create a selected p-tab

Utilizing the TabView module from primeng, I have created a dynamic tab where only the last tab remains static. The property used is 'selected', and for the dynamic tab, it is set as [selected]="'tab' + $index", where $index represents ...

The ng lint command is successful, yet an error appears in VS Code

I'm currently utilizing the tslint tool in my Angular project. Here is an excerpt from my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "downlevelIteration": true, "impor ...

Typescript - filtering out null values from JSON object

I am facing an issue with my service method that saves a date on the server. When this method sends the date to the server, it includes fields with null values in the JSON. How can I exclude these fields with null values? public create<T>(post: any) ...

Is there a circular dependency issue with ManyToMany relationships in Typescript TypeORM?

Below are the entities I have defined. The Student entity can subscribe to multiple Teachers, and vice versa - a Teacher can have many Students. import { PrimaryGeneratedColumn, Column, BeforeInsert, BeforeUpdate } from "typeorm" /* * Adhering to ...

The return type of Array.find is accurate, however, it contains an error

Trying to find a way to indicate the expected return type of Array.find() in TypeScript, I encountered an incompatibility warning. View code in playground class A { "type"="A" t: string; #a = 0 constructor(t: string) { ...

What are the possibilities of utilizing both Bootstrap 5 grid and Bootstrap 4 grid interchangeably?

After working with Bootstrap 4 in my Angular 12 project for some time, I decided to upgrade to Bootstrap 5 today. While I know that some properties have changed, I thought the grid system remained unchanged. I often use "Mix and Match" columns as describe ...

Technique in CSS/SASS to repair a div

Seeking a solution for fixing divs with text in CSS. I am aware of the background-attachment: fixed; property which creates a fancy effect. Is there a similar property to "fix" divs with text or how can this be achieved in Typescript? Your insight would be ...

What is the best way to set a checkbox to null instead of false using Angular?

I am currently developing a filtering system that allows users to select different parameters to filter through a list of items. For instance, the item list could be a collection of dishes with filters represented as checkboxes labeled as vegan, vegetaria ...