Detailed Explanation on Angular's NgIf, Else, Then
AngularJS is a complete client-side solution for building dynamic web pages. It is open-source JavaScript framework which can be freely used or shared by anyone. With this outline, one can now extend HTML with the new attributes called directives. For any AngularJS application, directives are considered as the most important components. Although there are huge built-in directives to deliver functionality to applications, one can also create application-specific directives. Here are a few Angular directives and their use in an Angular application –
NgIf - NgIf is that Angular directive which is used to add or eliminate the host element in DOM layout during the execution. Basically, NgIf runs with either true or false value as per the expression. In simple words, when the condition is true, elements will be added to DOM unless they all removed.
The directive NgIf can be used in multiple ways. On placing NgIf on an element, it recreates the elements during the compiled state and due to which the added class will be lost. Once the expression evaluated, Angular is used to add or eliminate the DOM nodes, mount or remount the components from DOM. The syntax of NgIf directive is simple, prefixing the directive with (*) and add it anywhere inside the template.
*NgIf and Else - Basically, the Else statement is used to display some false values. It is an amazing and easy-to-use addition to the AngularJS. If/else is useful in managing the messy templates or mount/unmount the components as well. When <ng-template> use the Else block, NgIf directive uses the reference variable to display the block when the condition is false.
*NgIf with Then and Else - Using “then” along with NgIf is simply used to move the initial *NgIf template outside the element. It is completely flexible to use in the cases where we want to dynamically change the template to then-. One can also adopt this approach to create more descriptive if/then/else block. By using the “then” block, all the content between the opening and closing tags of the bound element is ignored.
NgIf with “then” & “Else” can be used with the <ng-template> where the “then” is inline of the NgIf. As the result, when a condition is true, then <ng-template> with “then” block is executed. On the other side, when it is false, the <ng-template> with “Else” block is executed. One can also change the values for both “then” and “else” block at runtime. Only at one time, either the <ng-template> with “Then” or “Else” will run.
Angular JS directives are the most powerful components when used with HTML elements to create reusable code. In order to understand the coding in a better way, you can visit CodeFights Today. This platform helps you in solving all complex codes and prepare for technical interviews.