DEV Community

Cover image for Angular : Show Alert Message on a condition
RajeshKumarYadav.com
RajeshKumarYadav.com

Posted on • Updated on

Angular : Show Alert Message on a condition

How to create Alert?

You can use your custom CSS to customize your alert message or you can use Bootstrap Alert as below -

<div class="alert alert-success" role="alert">
  A simple success alert—check it out!
</div>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Now you know how to create Alert, now let's talk about how you can include bootstrap in your angular project so that bootstrap classes will work, there are two many ways to do this but I will simply use CDN style path in index.html

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
Enter fullscreen mode Exit fullscreen mode

Above code you need to paste in your index.html file inside <head> tag.

How to convert alert to conditional alert?

Now let's talk about how this alert will be conditional -

app.component.html

<p class="alert alert-success" *ngIf="names.length > 2">Currently there are more than 2 names!</p>
Enter fullscreen mode Exit fullscreen mode

Now you might get below error-

Error in src/app/app.component.html (5:39)
Property 'names' does not exist on type 'AppComponent'.

This is because you are using names in html which is not available in ts file, so you need to add this as -

app.component.ts

  names = ['Rajesh', 'John', 'Smith'];
Enter fullscreen mode Exit fullscreen mode

Now you will see -
Alt Text

Full Code and Demo -

Buy Me A Coffee

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

Top comments (0)