ng-if directive: The ng-if directive in AngularJS is used to remove or recreate a portion of the HTML element based on an expression. If the expression inside it is false then the element is removed and if it is true then the element is added to the DOM.
<element ng-if="expression"> Contents... </element>
- Consider a checkoff list made containing three items.
- Once all the items are bought then we display a message — “Everything is bought!”.
- At starting NG-IF removes this message from a portion of the DOM tree and based on the expression when it gets evaluated as true as it is recreated in DOM.
- To observe these changes we are going to inspect the code on Web Brower. Different ways to approach enable Inspect in Google Chrome:
- Menu bar -> More tools -> Developer tools.
- Right Click in the browser -> Inspect
- Ctrl + Shift + I (Windows)
- Cmd + Opt + I (Mac OS)
Note: For more information go to chrome-inspect-element-tool-shortcut.
Before Clicking all buttons: Here, we have three buttons to click and buy respective items.
In Inspect window: we can see that ng-if is commented out and a part of the DOM tree as expression evaluated to be False.
After Clicking all buttons: As we have clicked all the buttons and purchased every item, a message is displayed on the screen.
In Inspect window: we can see that ng-if is now not commented anymore and now it is a part of the DOM tree as expression evaluated to be True.
This gif output shows what all is happening.
- How to use ngIf without an extra element in Angular2?
- How to use *ngIf else in AngularJS ?
- How to check if an element is visible in DOM ?
- How to check an element is visible or not using jQuery?
- How to hide/visible the backside of a rotated div element using CSS ?
- How to check if a scrollbar is visible?
- jQuery | :visible Selector
- Fabric.js | Text visible Property
- How to select all visible or hidden elements in a HTML page using jQuery ?
- Fabric.js | Ellipse visible Property
- Fabric.js | Rect visible Property
- How to fix number of visible items in HTML dropdown and allow multiple selections ?
- How to count text lines inside of DOM element ?
- How to Remove HTML element from DOM using AngularJS ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.