if else statement in AngularJS templates.
If else statement in AngularJS.
361
17-Jun-2024
Updated on 18-Jun-2024
Ashutosh Kumar Verma
18-Jun-2024If-else in AngularJS
In AngularJS, you typically use directives like ng-if, ng-show, and ng-switch to create condition statements directly in your HTML templates, rather than using traditional JavaScript if-else statements
Using ng-if
Removes or reconstructs a portion of the DOM tree based on the
ng-ifspecification. It is often used to represent different things in a situation.Using ng-show
ng-showConditionally shows or hides objects based on the expression by removing them from the DOM.Using ng-switch
ng-switchuses conditions to change the DOM structure based on the value.Using JavaScript if-else in AngularJS
AngularJS does not encourage the insertion of JavaScript if-else statements directly into templates for arguments. Instead, you need to prepare the necessary data or boolean expressions in your controller or component, and use the Angular instructions shown above to implement the conditional definition.
Example-
A simple AngularJS program shows how to use of
ng-ifdirectives.In the example above
A variable
IsLogincreated within the controller and assigned a default valuefalse.Login()called when button is clicked that changes the value ofIsLoginvariable.data-ng-ifchecks the value ofIsLogin, if the value is true then that HTML element is visible otherwise hide.Also, Read: How to set focus on input field in AngularJS?