Conditional display of elements/data using Angular Js Directives. – User friendly Tech help
Today we would learn frequently used Angular JS directives.
n
Problem:- How to achieve conditional construct in Angular js?
n
Solution:- We would achieve it by using built in directives of Angular JS.
n
n
1. ng-Switch:-We can control the conditional display of data.
n
It is similar to Switch-Case in JavaScript.
n
JavaScript syntax:-
nSwitch(expression) {
n
Case n:n Code n Break;n Case n1:n Code n Break;n Default:n Default code
n
Angular JS syntax:-
nLets have corresponding code for above flow using directives:-
nng-switch on = expression
n
ng-switch-when = n Code ng-switch-when = n Code ng-switch-defaultn Code
n
nWe also need to use ng-switch-when & ng-switch-default directives same as Case and Default in Javascript
n
Example:-
n
n
EnterColor: I am very RED I am very GREEN I am default
n
n
2. ng-If:- Used to remove/recreate the DOM element based on the expression.
n
Syntax:- ng-if=”Conditional-Expression“
n
n
Note:-when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored.
n
Example:-
n
n
Check for Red Color:
n
n
n
Working Code
n
3. ng-Show/ng-Hide:-
nUsed to show/hide the DOM element based on the expression.
n
n
Note: – Unlike ng-if, it is not deleting and recreating the element from DOM but simply changing the display CSS of the element.
n
n
Syntax:-ng-Hide=”expression“
n
n
How it works: –
n
- n
- All it uses is Class =”ng-hide” and this class have CSS property of “display:none !important”.
- !important so that this property have the maximum weight and cannot be overridden.
- When expression is true then .ng-hide CSS is added causing element to be hidden and vice-verse.
n
n
n
n
Note: – For ng-Show we have ng-hide class added on “False” condition and removed when condition is “true” (it is reverse case as of ng-Hide)
n
nExample:-
n
Show Me: Hide Me:
n
- n
- We can check the ng-hide class, using the inspect element.
n
n
At launch of code
nCheck the “Show Me” checkbox