Angular, Software Development

Angular ngIf-else with ng-template Example

This post briefly demonstrates how to create an if-else statement in HTML using Angular ngIf-else with ng-template.

Stuff Used

We are going to use the following items for this post.

  • Angular 9
  • Nodejs 12.16.3
  • WebStorm – Optional

Create an Angular Project

Since this is just a brief post, here are the quick commands to create an Angular project and components before we can implement the if-else statement with ng-template. This post assumes that we already installed node and Angular CLI. On the command-line prompt window, run the following command that creates an Angular project.

The command generates the following output, and we need to choose some options along the way.

Then, we change the current directory to the angular-demo folder and run the npm install command.

At this point, we are almost ready to code. Finally, let us create a component using the following command.

The command will generate the following output.

Angular Component Codes

Initially, we set serverName to an empty string and use $event to get the value from the user as he types in some texts.

Moreover, we have the function onUpdateServerName, which is triggered by an event in the HTML.

HTML Codes Using ngIf-else With ng-template

Now, let us look at the HTML file servers.component.html that we generated together with our component. We use the (input) event with onUpdateServerName($event) . The if-else statement is on line 3, but with the display for else refers to an ng-template element with a unique identifier of noServer. Therefore, the else statement on line 3 will trigger the ng-template to display.

Lastly, we need to use the component’s selector in the app.component.html to test the Angular ngIf-else with ng-template. So, let us replace its content with the following codes.

Demo ngIf-else With ng-template

Finally, we start up the Angular application using the following command.

The command generates the following output.

Then, head to http://localhost:4200.

At this point, we successfully used Angular ngIf-else with ng-template.

This is now part of the Easy Angular Tutorial.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like