Search

Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from. If you’re new to AngularJS, it is better to get introductory information from. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. Introduction  Expressions In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. We will learn about each type of Expression in detail. The topics we will go through in this article are: Introduction to Expressions AngularJS Examples AngularJS using Numbers AngularJS using Strings AngularJS using Objects AngularJS using Arrays AngularJS Expression Capabilities and Limitations. Expressions in AngularJS Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: Can be written inside double braces: {{ expression }}. Can also be written inside a directive: ng-bind="expression". AngularJS will resolve the expression, and return the result exactly where the expression is written. Much like JavaScript expressions, they can contain literals, operators, and variables. Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} * Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. AngularJS Expressions and JavaScript expressions Let us compare Expressions in AngularJS and JavaScript. Similarity between AngularJS Expressions and JavaScript expressions: AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. Differences between AngularJS Expressions and JavaScript expressions: Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. Instead use services like $window and $location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. It is possible to access the context object using the identifier this and the locals object using the identifier $locals. AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's $parse service processes these expressions. Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. Filters: You can use filters within expressions to format data before displaying it. No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. No Bitwise, Comma, And Void Operators: You cannot use Bitwise, or void operators in an AngularJS expression. Citation: (Docs from AngularJS) Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. AngularJS expressions support filters, while JavaScript expressions do not. AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. AngularJS expression cannot declare functions. AngularJS expression cannot contain comma or void. AngularJS expression cannot contain return keyword. There are several categories in which Expressions operate. Some of the Expression Types are: Expressions Using numbers. Example: <p>Expense on Books : {{cost * quantity}} Rs</p> Expressions Using strings. Example: <p>Hello {{student.firstname + " " + student.lastname}}!</p> Expressions Using object. Example: <p>Roll No: {{student.rollno}}</p> Expressions Using array. Example: <p>Marks(Math): {{marks[3]}}</p> Let us go through each category in detail. Expression using Numbers Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   Say if we use the expression as:               <p>My first expression: {{ 5 + 5 }}</p> Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in:              My first expression: 10 We will understand more about the use of number expression in AngularJS with examples. Example:Considering you have already downloaded the latest AngularJS file from (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.jsExample Using Curly Braces {{ }} for expressions: <!DOCTYPE html>  <html>  <head>  <title>Number Expression of AngularJs</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = 10;  $scope.expr2 = 20  });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>Number Expression</div>  <p>The Result of Addition is : {{expr1 + expr2}}</p>  </div>  </form>  </body>  </html> Now run the number expressions as an HTML file and check the output, which will look like this:Example Using ng-init and ng-bind for number expressions: <!DOCTYPE html>  <html>  <head>  <title>Number Expression of AngularJs</title>  <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js">  </script>   </head>  <body>  <div ng-app="" ng-init="expr1=10; expr2=20">  <form id="form1">    <p>  The Result of Addition is :    <div ng-bind="expr1 + expr2"></div>  </p>    </form>  </div>  </body>  </html> Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: Expression using String Expression using String in AngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function.   * Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false.  For example:var obj1 = 123;   var obj2 = "A String value";   $scope.isString1 = angular.isString(obj1);   $scope.isString2 = angular.isString(obj2);  isString1 returns false while isString2 returns true. We will see how to use string expressions in detail in AngularJS with the following example: Example:<!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = "Hello ";  $scope.expr2 = "World";  $scope.expr3 = 100;  var nexpr = $scope.expr3;  var sexpr = $scope.expr1;  $scope.isString1 = angular.isString(sexpr);  $scope.isString2 = angular.isString(nexpr);  });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>String Expression</div>  <p>  The Result of Concatenation of {{expr1}} and {{expr2}} is :   {{expr1 + expr2}}  </p>  <p>  The Result of angular.isString() for parameter   {{expr1}} is : {{isString1}}  </p>  <p>  The Result of angular.isString() for parameter   {{expr3}} is : {{isString2}}  </p>  </div>  </form>  </body>  </html> Now run the String expressions as an HTML file and check the output, which will look like this: Expression using Object The object expressions in AngularJS hold object properties in them. AngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section:  Objects in AngularJS Before moving forth we need to understand objects in AngularJS.  AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. For Example: Considering an object as AngularTraining with fields as Trainer, noOfStd, noOfHours, it can be defined as: $scope.AngularTraining = {  Trainer: ‘Monica’,  noOfStd: 10,  noOfHours: 24  };  To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. Note that $scope in AngularJS is a built-in object which basically binds the “controller” and the “view”. One can define member variables in the $scope within the controller which can later be accessed by the view. We will see how to use object expressions in detail in AngularJS with the following example: Example:<!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.AngularTraining = {  Trainer: 'Monica',  noOfStd: 10,  noOfHours: 24  };   });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>  <p>  Pure JSON object contains key value pairs as Object Expression  </p>  </div>  <p>  The AngularTraining Object is:  <br/>  AngularTraining.Trainer: {{ AngularTraining.Trainer}}   <br/>  AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}   <br/>  AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}    </p>  </div>  </form>  </body>  </html> Now run the Object expressions as an HTML file and check the output, which will look like this:Objects with ng-init definition: We can define the objects at ng-init as shown in the following example: <!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  </head>  <body>  <form id="form1">  <div div ng-app="" ng-init = " AngularTraining = { Trainer: 'Monica',  noOfStd: 10, noOfHours: 24 }" >  <div>  <p>  Pure JSON object contains key value pairs as Object Expression  </p>  </div>  <p>  The AngularTraining Object is:  <br/>  AngularTraining.Trainer: {{ AngularTraining.Trainer}}   <br/>  AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}   <br/>  AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}    </p>  </div>  </form>  </body>  </html> Now run the Object expressions as an HTML file and check the output, which will look like this: Expression using Array Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. Arrays in AngularJS An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. For example:marks = [95, 52, 65, 98, 55, 35]; We will see how to use array expressions in AngularJS with the following example: Example:<!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.name = "Monica";  $scope.leave = [1, 2, 0];  });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>  <p>  Array Expression</p>  </div>  <p>  The Leave Report for the first quarter for Employee: <br/>  {{name}} is:  <br/>  January: {{ leave[0] }}   <br/>  February: {{ leave[1] }}    <br/>  March: {{ leave[2] }}    <br/>  Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}   </p>  </div>  </form>  </body>  </html> Now run the Array expressions as an HTML file and check the output, which will look like this:Defining Arrays with ng-init definition: We can define the arrays at ng-init as shown in the following example: <!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  </head>  <body >  <form id="form1">  <div div ng-app="" ng-init = " name = 'Monica'; leave = [1, 2, 0]; " >  <div>  <p>  Array Expression</p>  </div>  <p>  The Leave Report for the first quarter for Employee: <br/>  {{name}} is:  <br/>  January: {{ leave[0] }}   <br/>  February: {{ leave[1] }}    <br/>  March: {{ leave[2] }}    <br/>  Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}   </p>  </div>  </form>  </body>  </html> Now run the Array expressions as an HTML file and check the output, which will look like this: Complete ExampleSummarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS A complete example of AngularJS expression is: <!DOCTYPE html>  <html>     <head>        <title>AngularJS Expressions</title>     </head>     <body>        <h1>Expression</h1>  <div ng-app = "" ng-init = "quantity = 2; cost = 30; student = {firstname: 'Monica', lastname: 'Gupta', rollno: 34}; marks = [80, 90, 75, 73, 80] ">  <p>Hello {{student.firstname + " " + student.lastname}}!</p>  <p>Expense on Books : {{cost * quantity}} Rs</p>  <p>Roll No: {{student.rollno}}</p>  <p>Marks(Math): {{marks[3]}}</p>  </div>  <script src = "angular.min.js"></script>  </body>   </html> Now run the Expressions as an HTML file and check the output, which will look like this: AngularJS Expression capabilities and Limitations AngularJS Expression capabilities Angular expressions have the same power and flexibility as JavaScript expressions.  In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. In AngularJS expressions you can use filters within expressions to format data before displaying it. Angular JS Expression limitations Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression You cannot declare functions in an AngularJS expression, not even inside ng-init directive. You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \ $ etc. Such expressions cannot be used within AngularJS expressions. Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. ConclusionAngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{{ attrBinding }}">{{ textBinding }}</span>. Some valid expressions are: 1+2, a+b, user.name, items[index] . Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Learn AngularJs Expressions With Examples

9K
  • by Monica Gupta
  • 19th Sep, 2020
  • Last updated on 17th Mar, 2021
  • 12 mins read
Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   

Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  

AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. 

AngularJS can be downloaded from. 

If you’re new to AngularJS, it is better to get introductory information from. This site provides the basic information required to start working with AngularJS. 

It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. 

Introduction  

Expressions 

In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. 

We will learn about each type of Expression in detail. 

The topics we will go through in this article are: 

  • Introduction to Expressions 
  • AngularJS Examples 
  • AngularJS using Numbers 
  • AngularJS using Strings 
  • AngularJS using Objects 
  • AngularJS using Arrays 
  • AngularJS Expression Capabilities and Limitations. 

Expressions in AngularJS 

Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: 

  • Can be written inside double braces: {{ expression }}. 
  • Can also be written inside a directive: ng-bind="expression". 
  • AngularJS will resolve the expression, and return the result exactly where the expression is written. 
  • Much like JavaScript expressions, they can contain literals, operators, and variables. 

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} 

* Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. 

AngularJS Expressions and JavaScript expressions 

Let us compare Expressions in AngularJS and JavaScript. 

Similarity between AngularJS Expressions and JavaScript expressions: 

  • AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. 

Differences between AngularJS Expressions and JavaScript expressions: 

  • ContextJavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. 
    • AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. 
    • Instead use services like $window and $location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. 
    • It is possible to access the context object using the identifier this and the locals object using the identifier $locals. 
    • AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's $parse service processes these expressions. 
  • Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. 
    • In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} 
    • It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} 
    • Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. 
  • FiltersYou can use filters within expressions to format data before displaying it. 
  • No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. 
    • Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. 
  • No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. 
  • No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. 
  • No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. 
  • No Bitwise, Comma, And Void OperatorsYou cannot use Bitwise, or void operators in an AngularJS expression. 

Citation: (Docs from AngularJS) 

Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: 

  • AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. 
  • AngularJS expressions support filters, while JavaScript expressions do not. 
  • AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. 
  • AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. 
  • AngularJS expression cannot declare functions. 
  • AngularJS expression cannot contain comma or void. 
  • AngularJS expression cannot contain return keyword. 

There are several categories in which Expressions operate. Some of the Expression Types are: 

  • Expressions Using numbers. Example: 
    • <p>Expense on Books : {{cost * quantity}} Rs</p> 
  • Expressions Using strings. Example: 
    • <p>Hello {{student.firstname + " " + student.lastname}}!</p> 
  • Expressions Using object. Example: 
    • <p>Roll No: {{student.rollno}}</p> 
  • Expressions Using array. Example: 
    • <p>Marks(Math): {{marks[3]}}</p> 

Let us go through each category in detail. 

Expression using Numbers 

Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   

Say if we use the expression as: 

              <p>My first expression: {{ 5 + 5 }}</p> 

Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in: 

             My first expression: 10 

We will understand more about the use of number expression in AngularJS with examples. 

Example:

Considering you have already downloaded the latest AngularJS file from (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js

Example Using Curly Braces {{ }} for expressions: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Number Expression of AngularJs</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.expr1 = 10; 
$scope.expr2 = 20 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div>Number Expression</div> 
<p>The Result of Addition is : {{expr1 + expr2}}</p> 
</div> 
</form> 
</body> 
</html> 

Now run the number expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Example Using ng-init and ng-bind for number expressions: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Number Expression of AngularJs</title> 
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"> 
</script>  
</head> 
<body> 
<div ng-app="" ng-init="expr1=10; expr2=20"> 
<form id="form1">   
<p> 
The Result of Addition is :  
 <div ng-bind="expr1 + expr2"></div> 
</p>   
</form> 
</div> 
</body> 
</html> 

Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: Learn AngularJs Expressions With Examples

Expression using String 

Expression using String iAngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function.   

* Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false.  

For example:

var obj1 = 123;  
var obj2 = "A String value";  
$scope.isString1 = angular.isString(obj1);  
$scope.isString2 = angular.isString(obj2); 
isString1 returns false while isString2 returns true. 

We will see how to use string expressions in detail in AngularJS with the following example: 

Example:

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.expr1 = "Hello "; 
$scope.expr2 = "World"; 
$scope.expr3 = 100; 
var nexpr = $scope.expr3; 
var sexpr = $scope.expr1; 
$scope.isString1 = angular.isString(sexpr); 
$scope.isString2 = angular.isString(nexpr); 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div>String Expression</div> 
<p> 
The Result of Concatenation of {{expr1}} and {{expr2}} is :  
{{expr1 + expr2}} 
</p> 
<p> 
The Result of angular.isString() for parameter  
{{expr1}} is : {{isString1}} 
</p> 
<p> 
The Result of angular.isString() for parameter  
{{expr3}} is : {{isString2}} 
</p> 
</div> 
</form> 
</body> 
</html> 

Now run the String expressions as an HTML file and check the output, which will look like this:
Learn AngularJs Expressions With Examples

Expression using Object 

The object expressions in AngularJS hold object properties in themAngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section:  

Objects in AngularJS 

Before moving forth we need to understand objects in AngularJS.  AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. 

AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. 

For Example: Considering an object as AngularTraining with fields as Trainer, noOfStdnoOfHours, it can be defined as: 

$scope.AngularTraining = { 
TrainerMonica, 
noOfStd10, 
noOfHours24 
};  

To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. 

Note that $scope in AngularJS is a built-in object which basically binds the controller and the view. One can define member variables in the $scope within the controller which can later be accessed by the view. 

We will see how to use object expressions in detail in AngularJS with the following example: 

Example:

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.AngularTraining = { 
Trainer: 'Monica', 
noOfStd: 10, 
noOfHours: 24 
};  
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div> 
<p> 
Pure JSON object contains key value pairs as Object Expression 
</p> 
</div> 
<p> 
The AngularTraining Object is: 
<br/> 
AngularTraining.Trainer{{ AngularTraining.Trainer}}  
<br/> 
AngularTraining.noOfStd{{ AngularTraining. noOfStd}}  
<br/> 
AngularTraining. noOfHours{{ AngularTraining. noOfHours}}  
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Object expressions as an HTML file and check the output, which will look like this:Learn AngularJs Expressions With Examples

Objects with ng-init definition: 

We can define the objects at ng-init as shown in the following example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
</head> 
<body> 
<form id="form1"> 
<div div ng-app="" ng-init = " AngularTraining = { Trainer'Monica',  noOfStd: 10, noOfHours: 24 }" > 
<div> 
<p> 
Pure JSON object contains key value pairs as Object Expression 
</p> 
</div> 
<p> 
The AngularTraining Object is: 
<br/> 
AngularTraining.Trainer{{ AngularTraining.Trainer}}  
<br/> 
AngularTraining.noOfStd{{ AngularTraining. noOfStd}}  
<br/> 
AngularTraining. noOfHours{{ AngularTraining. noOfHours}}  
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Object expressions as an HTML file and check the output, which will look like this: Learn AngularJs Expressions With Examples

Expression using Array 

Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. 

Arrays in AngularJS 

An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. 

For example:

marks = [95, 52, 65, 98, 55, 35]; 

We will see how to use array expressions in AngularJS with the following example: 

Example:

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.name = "Monica"; 
$scope.leave = [120]; 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div> 
<p> 
Array Expression</p> 
</div> 
<p> 
The Leave Report for the first quarter for Employee: <br/> 
{{name}} is: 
<br/> 
January{{ leave[0] }}  
<br/> 
February{{ leave[1] }}   
<br/> 
March{{ leave[2] }}   
<br/> 
Total Leave for the first Quarter is: 
{{ leave[0] + leave[1] + leave[2] }} 
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Array expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Defining Arrays with ng-init definition: 

We can define the arrays at ng-init as shown in the following example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
</head> 
<body > 
<form id="form1"> 
<div div ng-app="" ng-init = " name = 'Monica'; leave = [120]; " > 
<div> 
<p> 
Array Expression</p> 
</div> 
<p> 
The Leave Report for the first quarter for Employee: <br/> 
{{name}} is: 
<br/> 
January{{ leave[0] }}  
<br/> 
February{{ leave[1] }}   
<br/> 
March{{ leave[2] }}   
<br/> 
Total Leave for the first Quarter is: 
{{ leave[0] + leave[1] + leave[2] }} 
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Array expressions as an HTML file and check the output, which will look like this: 

Learn AngularJs Expressions With Examples

Complete Example

Summarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS 

A complete example of AngularJS expression is: 

<!DOCTYPE html> 
<html>    
<head>       
<title>AngularJS Expressions</title>    
</head> 
   <body>       
<h1>Expression</h1> 
<div ng-app = "" ng-init = "quantity = 2; cost = 30; student = {firstname: 'Monica', lastname: 'Gupta', rollno: 34}; marks = [80, 90, 75, 73, 80] "> 
<p>Hello {{student.firstname + " " + student.lastname}}!</p> 
<p>Expense on Books : {{cost * quantity}} Rs</p> 
<p>Roll No: {{student.rollno}}</p> 
<p>Marks(Math): {{marks[3]}}</p> 
</div> 
<script src = "angular.min.js"></script> 
</body>  
</html> 

Now run the Expressions as an HTML file and check the output, which will look like this: Learn AngularJs Expressions With Examples

AngularJS Expression capabilities and Limitations 

AngularJS Expression capabilities 

  • Angular expressions have the same power and flexibility as JavaScript expressions.  
  • In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. 
  • In AngularJS expressions you can use filters within expressions to format data before displaying it. 

Angular JS Expression limitations 

  • Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression 
  • You cannot declare functions in an AngularJS expression, not even inside ng-init directive. 
  • You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \ $ etc. Such expressions cannot be used within AngularJS expressions. 
  • Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. 

Conclusion

AngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. 

AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{attrBinding }}">{{ textBinding }}</span>. 

Some valid expressions are: 1+2, a+b, user.name, items[index] . 

Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. 


Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Monica

Monica Gupta

Author

I am Monica Gupta with 19+ years of experience in the field of Training and Development. I have done over 500 Corporate Trainings. I am currently working as a freelancer for several years. My core area of work is Java, C++, Angular, PHP, Python, VBA.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email in Node.js using the nodemailer npm package.For the email provider, we are going to use Sendinblue. Prerequisites Node.js (>v6.0.0 for nodemailer module) Code Editor (For Ex. VS Code, Atom) An account in SendinblueStart by creating a free account in Sendinblue. A Sendinblue free account offers 300 mails/day. Its setup is easy and straightforward. An introduction to Nodemailer Nodemailer, an open source project started in 2010, is annpm module for Node.js applications to send emails. Today, nodemailer is a de facto to send an email in Node.js. Highlights of Nodemailer It is a single module with zero dependencies  It supports HTML Content  Allows you to easily add attachments to messages Supports SMTP as default transport method; other supported transport methods are SES, Sendmail, Stream. OAuth2 authenticationGetting Started For this tutorial, I am using Nodejs v12.16.1 and VS Code as the Code Editor. Create a new directory nodemailer-example.  Open the terminal or cmd inside the directory and run  $ npminit --yes It will initialize a new npm package. Install dependencies Following different npm packages, we are going to use in this project. nodemailer – To send the mail express – To create APIs cors – To resolve the cross originresource sharing body-parser – To extract the body from the API request dotenv – To access the environment variables $ npm install --save nodemailer express cors body-parser dotenv This command will install all the dependencies. Now, we can start the coding. Project Structure Open the nodemailer-example in the code editor and create the following folders and files in it; not to worry, I will be explaining all the files and commands involved.  nodemailer-example    |- routes      |- mail-api.js    |- src      |- send-mail.js    |- template      |- mail.html    |- .env    |- index.js Sendinmail Setup Login to your Sendinmail account. From the top-left menu, select SMTP & API. Select the SMTP tab. Click on Create a new SMTP key. Copy the key at some safe place.  You can deactivate the SMTP key anytime. Now, open the .env file and create 2 key-value pair. USER=YOUREMAILADDRESS  PASS=xxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx USER: The email address using which you created the sendinmail account. PASS:SMTP Key By using .env file we are not exposing the credentials to the web.  Using environment variables in the project is an industrial standard.  Source Code Open the send-mail.js in the editor. Copy and paste the below code in it."use strict";  require("dotenv").config();  constnodemailer = require("nodemailer");  /**   * sendEmail   * @param{Object}mailObj - Email information   * @param{String}from- Email address of the sender   * @param{Array}to- Array of recipients email address   * @param{String}subject - Subject of the email   * @param{String}text - Email body   */  constsendEmail = async (mailObj) => {  const{ from, to, subject, text } = mailObj;  try {  // Create a transporter  lettransporter = nodemailer.createTransport({  host:"smtp-relay.sendinblue.com",  port:587,  auth: {  user:process.env.USER,  pass:process.env.PASS,        },      });  // send mail with defined transport object  letinfo = awaittransporter.sendMail({  from:from, // sender address  to:to, // list of receivers  subject:subject, // subject line  text:text, // plain text body      });  console.log(`Message sent: ${info.messageId}`);  return`Message sent: ${info.messageId}`;    } catch (error) {  console.error(error);  thrownewError(  `Something went wrong in the sendmail method. Error: ${error.message}`      );    }  };  module.exports = sendEmail; Code Walk Through In the beginning, we are importing dotenv to get the environment variables from the .env file and nodemailer to send the email. The sendEmailfunction accepts an object. This object has from, to, subject, text fields. Please note that, from and USER must be same. The nodemailer.createTransportreturns a mail object. The transporter variable is storing the mail object.  let transporter = nodemailer.createTransport({       host: "smtp-relay.sendinblue.com",       port: 587,       auth: {         user: process.env.USER,         pass: process.env.PASS,       },     });Open SMTP tab in your sendinmail account and cross check the host and port.In the auth object, we are passing the user and password from the environment variable.Send the mail using sendMail method.// send mail with defined transport object     let info = await transporter.sendMail({       from: from, // sender address       to: to, // list of receivers       subject: subject, // Subject line       text: text, // plain text body     });It returns a Promise of Send Message Info. In the end, it is returning the message id.  Express Route The sendEmail method is ready.  Let’s create an express route for it. This is the API endpoint using which we can access the sendEmail function. Open the mail-api.js in the code editor and paste the below code. constexpress = require("express");  constrouter = express.Router();  constsendMailMethod = require("../src/send-mail");  // Post request to send an email  router.post("/sendmail", async (req, res) => {  try {  constresult = awaitsendMailMethod(req.body);  // send the response  res.json({  status:true,  payload:result          });      } catch (error) {  console.error(error.message);  res.json({  status:false,  payload:"Something went wrong in Sendmail Route."          })      }  }) module.exports = router; The express framework provides a Router method to create different HTTP methods. Here, we have created a POST method to send the mail.  Instead of extracting the req.body parameters, we passed it as it is. The benefit of this approach is that if there is a change in argument or position, then we would not have to change it in all the places.  In the end, we are exporting the router. Now, this can be used in the server side. Express Server Now, it’s time to create a server and expose the routes on it. Open the index.js and paste the below code in it. "use strict";  constexpress = require("express");  constbodyParser = require("body-parser");  constcors = require("cors");  constapp = express();  constmailAPI = require("./routes/mail-api.js");  // Express body parser  app.use(cors());  app.use(bodyParser.json());  app.use(  bodyParser.urlencoded({  limit:"50mb",  extended:false,  parameterLimit:50000    })  );  // use the routes specified in route folder  app.use("/api/v1", mailAPI);  constport = process.env.PORT || 4444;  //listen to the server  app.listen(port, function () {  console.log(`listening to the port ${port} .....`);  }); The route is available on /api/v1/sendmail. Run the server. $ node index.js  listening to the port 4444 ..... Send an Email using API There are couple of methods to test the API. Using the Postmanor using the Curl command. Using Postman Install Postman on your machine if it is not installed. Create a POST request. URL: http://localhost:4444/api/v1/sendmail Content Type: JSON – Body tab > select JSON from dropdown Request Body:  {  "from": "hello@schadokar.dev",  "to": ["shubham@schadokar.dev"],  "subject": "Mail from Nodemailer",  "text": "Sending an email using nodemailer package."  } Hit Send. Make sure the server is running. On Success, the response returns the message id. Now, check your mailbox. If you are unable to find the mail in your Inbox, check the promotional mail folder. Using Curl CommandOpen the terminal or cmd.In the below curl command, change the parameters and enter.curl -X POST http://localhost:4444/api/v1/sendmail -H "Content-Type:application/json" -d '{"from": "hello@schadokar.dev","to": ["shubham@schadokar.dev"],"subject": "Mail from Nodemailer", "text": "Sending an email using nodemailer package."}'In this example, we have sent a simple text message to the recipient.  Nodemailer also gives you an option to send the message in HTML format. Mail template Open the mail.html in the code editor and paste the below code. 
6797
Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email ... Read More

Full Stack Development – the Hottest Developer Skill for the Digital Age

With over 1.7 billion websites worldwide and 4.54 billion people using the internet actively, the need for heightened customer experience is on the rise. This is one of the major reasons why professionals who are adept at handling both the client-side and server-side interfaces of an application/website have become more important than ever. It has been estimated that by the next decade, there will be 300,000 new developer jobs in US. The Full Stack developer role is the No.1 position to be filled in 2020 according to 38% of hiring managers. This is closely followed by the role of a back-end developer.Handsome pay packagesThe average annual salary for a full-stack developer is about $110,737 per annum. Even beginners are offered about $58,000 per year and on the other hand, experienced professionals would earn up to $188,253 per year.These professionals are paid handsomely because enterprises are aware that a full stack developer does the job of two professionals (back-end and front-end developer).Plenty of growth opportunitiesAs per reports by The United States Bureau of Labor Statistics, full-stack development job opportunities will increase from 135,000 to 853,000 by the year 2024. This is quite promising for aspiring full stack developers as an ocean of opportunities will be available for them in both startups as well as in multi-national organizations.Skills to become a Full Stack developerBecoming a full-fledged full stack developer is not child’s play. It takes a wide range of skills to become a good full stack developer. Below are the mandatory skills:Front-end skills: They should be well-versed with basic front-end technologies like HTML5, CSS3, and JavaScript. They should also be comfortable working with front-end frameworks or third-party libraries such as JQuery, SASS, and AngularJS.Programming languages: They should be aces in at least one server-side coding language like Java, Python, Ruby or .Net.Databases: They should be efficient at handling data from databases like MySQL, MongoDB, Redis, Oracle and SQLServer.Version control systems (VCS): Full stack developers must be aware of Git so that they can make appropriate changes to the codebase.Basic design skills: Awareness about the basic prototype design and UI/UX design is essential to become a successful full stack developer.Server and API: They should have adequate exposure to Apache or Linux servers as well as web services.The way forward for Full Stack developersThe growing demand for full-stack developers is due to the ample benefits they offer to organizations. With technology evolving at a rapid pace, foresighted companies will keep adding them to their workforces. Full stack development became the No.1 developer skill because these developers are trained to multi-task various technologies and products. For aspiring full stack developers out there, now is the best time to make the most of these opportunities.Real products require real challenges. Check out our live online workshops and build your portfolio of projects.
4858
Full Stack Development – the Hottest Develop...

With over 1.7 billion websites worldwide and 4.54 ... Read More

What are React Component Lifecycle Methods

React is the most popular JavaScript library used to create interactive UI for web applications. It is a component-based library where different parts of a webpage can be encapsulated by components which are quite easy to create, manage and update. React allows us to create Single Page Applications which maintain the state of individual components on an app without having to reload it.  What are React Components? Developers who are new to JavaScript libraries and frameworks like React and Angular might ask the question, “What is a component?” Well, in very simple words, a component is a unit of code which includes JavaScript and HTML to build a part of a web page. It acts like a custom HTML element. It is reusable and can be as complex as you want it to be. For example, imagine that you are creating a very basic application with header, footer, and body. The header can be a component; the footer can be another component and the body can be yet another one or even might consist of multiple components.One of the most useful characteristics of React is its ability to integrate reusable components in a project. Reusability is the characteristic of a component which allows it to be used again, thereby reducing the amount of code a developer has to write. In our example here, the header can be a reusable component and can be used on all the pages of the application, which makes it easy to maintain and update. What does a component look like? Here is a simple example of a react component which contains a simple form. This is a class-based component. React also supports function-based components. As you can see in the code below, App is a user-defined class which inherit from React’s Component class and it has a render method which returns HTML code. As the name suggests, the render method returns and renders HTML to our browser. Every component has to return HTML which is rendered to the user’s browser by render method.import React, { Component } from 'react';  class App extends Component {    handleChange(event) {      this.setState({value: event.target.value});    }    render() {      return (                              Username:                                            Password:                                              );    }  }    export default App; In the above example, we have created a login form where there are 2 input boxes for the user to enter their username and password and then submit the form. We have assigned an event handler to form which will handle the login event in component.We have exported our component (using export default App) so that it can be rendered inside other components.This is a very basic example of component, but this can be as complex as you want it to be. But it is always advised to make your component independent and it should represent only a part of your page which can be reusable as well. It can return complex HTML included with JavaScript to handle complex features in your application.Component as a class React allows us to create component in the form of class as well as functions. While creating component as class you need to define a class which extends React.Component class. Component class has many features which the deriving class can use to maintain the state throughout the lifecycle. In case you want to have more custom features, you can create your own base component class which derives from Component class, and then your component classes can derive from your base component class. What do we mean by Component Lifecycle?Lifecycle of a component is the set of different stages (also known as lifecycle hooks) a component goes through while it is active. Stages could be when a component is created or when any changes are made to the component and many others. There are different methods executed by React at different points of time between when a component is created and at the end when it is destroyed and not in use. One such hook or method we have already seen in the code above, which is render(), and it is executed by React to render the component. We can override these methods and perform certain tasks in those methods, but every lifecycle serves a different purpose and it can be a nightmare if we ask them to do something that they aren’t supposed to or are not very good at. As a developer we should be aware of what those different stages are, what happens in those stages, in what order they execute and how we can make the best use of it. Understanding the lifecycle of components also helps us predict behavior of a component at different stages, which makes it easier to work with them. Managing a large set of components in an application can get you in trouble if you do not know how they work behind the scenes.Props and State Before we start with lifecycle hooks, lets understand what props and state are as they are most commonly used properties in component classes. Props It is a keyword which means properties. Props are used by callers of components to pass properties to the called component in a uni-directional flow. For example, if Parent component renders child component, it can define props and pass them to the child component which is then available and accessible by this.props. Another thing to note here is that props is a ready-only attribute which means data which is passed by parent should not be changed by client components. State State is a plan JavaScript object which defines the current state of any component. It is user defined and can be changed by lifecycle hooks. Ideally state should contain only data which is going to be rendered on DOM. State has getter and setter methods this.getState() and this.setState() which as the names suggest are used to access and update State. It is good practice to use setState method to update State and treat State as an immutable JavaScript object.Since there are many lifecycle hooks a component goes through, it would easier to understand if we start with the hooks which are executed when a component is created.Lifecycle hooks while Mounting [These lifecycle hooks are executed in order as listed, when a component is created]constructor(props) This is not a component lifecycle hook, but it is important to mention here and to be aware that Constructor is executed before it is mounted. Constructor receives props(properties of a component) as an argument which then can be passed to base class using super keyword if we define the constructor.  It is not mandatory to define constructor in component class, but if you do to perform any logic, then you need to call base constructor using super keyword.  Mainly constructors are used: To Setup local state of component with this.state To bind event handler methods. This is what a simple constructor would look like.import React, { Component } from 'react';  class App extends Component {    constructor(props) {      super(props);      this.state = { value: 0 };      this.handleClick = this.handleClick.bind(this);    }  } this.state should be called only inside constructor, to update the state in other methods use this.setState() method.  If constructor is required to do any heavy tasks, it will impact the performance of component, and you should be aware of this fact.  getDerivedStateFromProps(props, state) After constructor, this lifecycle hook is called before render method is executed. It is called while mounting as well as whenever props have changed. This is not very commonly used, only in cases where props can change, and you need to update state of the component. This is the only use case where you should implement this lifecycle hook.This method is executed on every render and cannot access component instance.import React, { Component } from 'react';  class App extends Component {    getDerivedStateFromProps(props, state) {      if (props.value !== state.prevValue) {        return {          prevValue: props.value        };      }      return null;    }    }render() This is the method which is required to be implemented in component class. It can access props and state. This is where you can write your html and jsx code. You can also render child components in this method which will then be rendered as well. Before completing the lifecycle of parent, lifecycle of all child components will be finished. All this html and jsx is then converted to pure html and outputs in DOM. JSX is a JavaScript extension which creates React elements. It looks more like template language but it is empowered by JavaScript which allows it to do a lot more. It can embed expressions . JSX has different set of attributes than what we have in html. For example, while creating html using JSX you need to use attribute “className” instead of class. This is what a typical render method looks like:import React, { Component } from 'react';   class App extends Component {   render() {         return (        Click to go Home { this.state.home }       Go to Home         );   } } Alternatively you can also use React.createElement() method to create html using JSX.const element = React.createElement(       'h1',       {className: 'hello'},       'Hello, world!'     );componentDidMount() As the name suggests, componentDidMount() is invoked after the component is mounted, which means html has been added to DOM tree. It is a very commonly used lifecycle hook, as it allows you to do a lot of things including causing side-effects, setting up any subscriptions, or loading data from external endpoints. If you setup any subscription using this method, make sure to unsubscribe them in componentWillUnmount() lifecycle hook. You shouldn’t update state in this method using this.State() as it may cause performance issues. For assigning initial state you should use constructor(). import React, { Component } from 'react';  class App extends Component {    componentDidMount(){    // Component is rendered and now external calls can be made.      this.getDataAfterTimeOut();    }    getDataAfterTimeOut(){      setTimeout(() => {        this.setState({          data: 'Data is fetched'        })      }, 1000)    }  } Lifecycle hooks while Updating [Next set of lifecycle hooks are executed while a component is updating which can be caused by changes to props(properties) or state of component. These are invoked in order as listed below.] getDerivedStateFromProps(props, state) We have already talked about this. This is invoked every time a component is changed or updated. Any changes in properties or state which causes the component to be changed will invoke this method. shouldComponentUpdate(nextProps, nextState) shouldComponentUpdate() is invoked before rendering (not on initial rendering) but only when props or state has been changed. Even though it is not recommended you can use this lifecycle hook to control the re-rendering. This can lead to performance issues as well as bugs, so be careful while doing that.  In this method nextProps can be compared with this.props and nextState can be compared with this.state. This method can return true or false depending on whether you want to continue rendering by skipping the next lifecycle hooks. In either case it can’t prevent re-rendering of child components. Note that this method defaults to true which will not skip rendering and next lifecycle hooks and continue with execution. import React, { Component } from 'react';  class App extends Component {    shouldComponentUpdate(nextProps, nextState) {  // This value will determine if lifecycle execution is to be skipped or continued.      return nextProps.value != this.props.value;    }  } render() After shouldComponentUpdate lifecycle hook render is called, which we have already talked about, it prepares html and jsx code which then outputs to DOM. getSnapshotBeforeUpdate() getSnapshotBeforeUpdate() is invoked right before the recent changes are added to DOM. This lifecycle hook gives us an opportunity to capture any details we need from the DOM before it is updated with new content. For example, if you want to know the scrolling position of the user, which should be restored after the DOM has changed. Use cases for this lifecycle, while rare, can be of great value at times. The snapshot value which is captured and returned by this hook is passed as a parameter to another lifecycle hook componentDidUpdate() which we will talk about next. import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate (prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      if (this.state.value != prevState.value) {        return table.scrollHeight - table.scrollTop      }      return null    }  }componentDIdUpdate(prevProps, prevState, snapshot) componentDidUpdate is invoked when DOM is updated. It is only called on update, not on initial rendering. You can use this method to make data requests after checking if props have changed. You can also call setSatate() in this method, but make sure to wrap that in a condition else it will cause an infinite loop forcing re-rendering and affecting performance issues. Also it should be noted that value for snapshot will only be available if you have implemented getSnapshotBeforeUpdate() in your component; else value for snapshot will be undefined. Here is an example of componentDidUpdate. This is a very basic example where we have captured snapshot by implementing get Snapshot Before Update lifecycle hook. After that componentDidUpdate is invoked and content is overwritten with new dataimport React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } UnMounting [This is where lifecycle of a component ends when component is destroyed and removed from DOM. While Unmounting React gives us an opportunity to do something before component is destroyed, it can include clearing objects which have occupied memory to avoid memory leaks.] componentWillUnMount() componentWIllUnMount() is executed right after component is unmounted which means it is removed from DOM and destroyed. But before it is removed and destroyed, React gives us an opportunity to perform any cleanup we want to. For example, you might have setup subscriptions initially in componentDidMount() which you should unsubscribe when component is destroyed to avoid memory leaks in your application. You can also remove event listeners which were subscribed before. In this lifecycle hooks you should not update state of your component because component is not going to re-render now.import React, { Component } from 'react';  class App extends Component {    componentWillUnmount() {  // Component will be removed from DOM now.        // Unscubscribe subscriptions and events here.  document.removeEventListener("click", this.handleSubmit);    }  }Conclusion In this article we talked about React, its components and its different lifecycles. It is very crucial to understand the different opportunities that React provides through these lifecycle methods. There are many rules we need to follow while working with these hooks. Making them do something they can’t handle can cause performance issues or even infinite loops at times.  These lifecycle hooks work with props and state which are the most used properties of component class. Changes in state and props trigger different lifecycle hooks and even re-render the dom which is something you should be aware of. These lifecycle hooks are provided to intercept the different stages a component goes through and make the best use of it, but without understanding how they work it can break your application by causing performance issues or memory leaks. Hope this has been helpful. 
9274
What are React Component Lifecycle Methods

React is the most popular JavaScript library us... Read More