$emit, $broadcast, $on – Part2

$emit: It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast: It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on: It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.

  • And now creating the script, here myController is the controller which is going to emit/broadcast an event with some arguments.
  • parentController1, parentController2 will listen to event which is dispatched from myController by $broadcast.
  • childController1, childController2 will listen to event which is dispatched from myController by $emit.

 

output

  • In this example we have used $scope context to $emit/$broadcast the events, and $on has listened all the events by using $scope.$on().
  • Now if we have used $rootscrope context to $emit/$broadcast, it will not work same as that works with $scope.
  • Because $rootscope is the parent scope and it doesn’t have any parent, when we emit using $rootscope.$emit(), only $rootscope.$on() can listen to that events. Whereas when we broadcast using $rootscope.$broadcast(), all the $rootscope.$on() and $scope.$on() can listen to that event.

 

 

Cancelling Events:

Canelling event is possible when event is emitted, but we cannont cancel the event when it is broadcasted.

  • If the event is dispatched by using $scope.$emit( ) then any of the $rootscope/$scope listeners can cacel it.
  • If the event is dispatched by using $rootscope.$emit() then any of the $rootscope listeners can cancel it.

$emit, $broadcast, $on – Part1

$emit, $broadcast, $on – Part1

How to use $rootScope:

As we know that $rootScope is the parent for $scope, to override the $rootScope we need to re-initialize the $rootScope variable with $scope

Let us see an example

In this example we have injected $rootScope in both parent and child controllers.

As $rootScope variables will be available throughout the application we can now access the $rootScope variable anywhere in the application by just injecting the $rootScope

Output:

  • Now if we remove the $rootScope from Parent and initialize it in child controller, it works same.

Output:

How to pass data from parent controller to child

To pass the data from Parent Controller to Child, we need to extract parent controller $scope variable using $parent.

Example: In this example we will use only $scope.

How to pass data from child controller to parent

To pass data from child to parent controllers using $scope we don’t have $child to take from child controller. But here I’ll show you one of the possible way to transfer data.

  • In child controller initialize the empName in an object as $scope.employee.empName.
  • In parent controller declare an empty object naming with same object as $scope.employee = {}

Output:

$emit, $broadcast, $on – Part2

Automation Test Life Cycle

Once you start automating test script you will get this work often. We talk about life cycle it mean end to end picture of that scenario, like we have a life cycle for development, for manual testing similarly we have in Automation as well. Today in this post we will discuss Automation test life cycle in short ATLC.

You all must be familiar with SDLC ( Software development life cycle ), STLC ( Software test life cycle ), so lets discuss ATLC ( Automation test life cycle ).

Please refer  below image is the ATLC (Automation test life cycle diagram)

Automation test life cycle has 6 section

1- Automation feasibility analysis

2- Test Plan/Test Design

3- Environment Setup/Test lab setup

4-Test Script development/ Automation test case development

5-Test script execution

6- Generate test result / Analyses of  result

 

Lets start  each of the phase of Automation test life cycle

1- Automation feasibility analysis

  • The main objective of this phase will be to check feasibility of automation. 
  • Which test case can be automated and how we can automate them.
  • Which module of your application can be tested and which can not be automated
  • Which tools we can use for our application (like Selenium, QTP, Sahi, OATS, Telrik etc) and which tools will be best of our application
  • Take following factors into consideration like Team size, Effort and cost involved for tools which we will use.

2- Test Plan/Test Design

  • In this phase you have to create a Test plan by considering below point into considerations.
  • Fetch  all the manual test case from test management tool that which TC has to automate.
  • Which framework to use and what will be advantage and disadvantage  of the framework which we will use.
  • Create a test suite for Automation test case in Test Management tool.
  • In test plan you can mention background, limitation, risk and dependency between application and tools.
  • Approval from client/ Stack holders.

3- Environment Setup/Test lab setup 

By name itself you can understand that we need to setup machine or remote machine where our test case will execute.

  • In this section you can mention how many machine you want.
  • What should be the configuration in terms of hardware and software

4- Test Script development/ Automation test case development

In this phase you have to start develop automation script and make sure all test script is running fine and should be stable enough.

  • Start creating test script based on your requirement
  • Create some common method or function that you can reuse throughout your script
  • Make your script easy, reusable,well structured and well documented so if third person check your script then he/she can understand your scripts easily.
  • Use better reporting so in case of failing you can trace your code
  • Finally review your script and your script should be ready before consumption.

5 – Test script execution
Now its time for execution of test scripts, in this phase you have to execute all your test script.
Some points to remember while execution

  • Your script should cover all the functional requirement as per test case.
  • Your script should be stable so it should run in multiple environment and multiple browsers (depends on your requirement)
  • You can do batch execution also if possible so it will save time and effort.
  • In case of failure your script should take screen shots.
  • If test case is failing due to functionality, you have to raise a bug/defect.

 6- Generate test result / Analyses of  result

This is the last phase of Automation test life cycle in which we will gather test result and will share with team/client/stack holders.

  • Analyze the output and calculate how much time it take to complete the testcase.
  • You should have good report generation like XSLT report, TestNG report, ReporterNG etc.

Selenium Interview Questions

What is Automation Testing?

Automation testing or Test Automation is a process of automating the manual process to test the application/system under test. Automation testing involves the use of a separate testing tool which lets you create test scripts which can be executed repeatedly and doesn’t require any manual intervention.

What are the benefits of Automation Testing?

Benefits of Automation testing are:

  • Supports execution of repeated test cases
  • Aids in testing a large test matrix
  • Enables parallel execution
  • Encourages unattended execution
  • Improves accuracy thereby reducing human-generated errors
  • Saves time and money

Why should Selenium be selected as a test tool?

Selenium

  • is a free and open source
  • have a large user base and helping communities
  • have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
  • have great platform compatibility (Windows, Mac OS, Linux etc.)
  • supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
  • has fresh and regular repository developments
  • supports distributed testing

What is Selenium? What are the different Selenium components?

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web-based applications and a wide range of browsers and platforms. Due to its existence in the open source community, it has become one of the most accepted tools amongst the testing professionals.

Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason, it is referred to as a Suite. Each of these tools is designed to cater different testing and test environment requirements.

The suite package constitutes of the following sets of tools:

  • Selenium Integrated Development Environment (IDE) – Selenium IDE is a record and playback tool. It is distributed as a Firefox Plugin.
  • Selenium Remote Control (RC) – Selenium RC is a server that allows a user to create test scripts in the desired programming language. It also allows executing test scripts within the large spectrum of browsers.
  • Selenium WebDriver – WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility to automate.
  • Selenium Grid – Selenium Grid is used to distribute your test execution on multiple platforms and environments concurrently.

What are the testing types that can be supported by Selenium?

Selenium supports the following types of testing:

  • Functional Testing
  • Regression Testing

What are the limitations of Selenium?

Following are the limitations of Selenium:

  • Selenium supports testing of only web-based applications
  • Mobile applications cannot be tested using Selenium
  • Captcha and Barcode readers cannot be tested using Selenium
  • Reports can only be generated using third-party tools like TestNG or JUnit.
  • As Selenium is a free tool, thus there is no ready vendor support through the user can find numerous helping communities.
  • The user is expected to possess prior programming language knowledge.

When should I use Selenium IDE?

Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its record and playback feature make it exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

What are the different types of locators in Selenium?

The locator can be termed as an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely we have different types of locators in Selenium:

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector

What is the difference between assert and verify commands?

Assert: Assert command checks whether the given condition is true or false. Let’s say we assert whether the given element is present on the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the execution would stop and no further test would be executed.

Verify: Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the program execution doesn’t halt i.e. any failure during verification would not stop the execution and all the test steps would be executed.

What is an XPath?

XPath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being markup languages and since they fall under the same umbrella, XPath can be used to locate HTML elements.

The fundamental behind locating elements using XPath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.

What is the difference between “/” and “//” in Xpath?

Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.

Double Slash “//” – Double slash is used to create Xpath with relative path i.e. the xpath would be created to start selection from anywhere within the document.

When should I use Selenium Grid?

Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution, testing under different environments and saving execution time remarkably.

How do I launch the browser using WebDriver?

The following syntax can be used to launch Browser:

What is a framework?

 

The framework is a constructive blend of various guidelines, coding standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data injections etc. to pillar automation testing.

What are the advantages of Automation framework?

The advantage of Test Automation framework

  • Reusability of code
  • Maximum coverage
  • Recovery scenario
  • Low-cost maintenance
  • Minimal manual intervention
  • Easy Reporting

Java Interview Questions:

  1. Difference between Overloading and over riding

Method over Loading:

  • Method Overloading is performed with in Class
  • In Case of method overloading, Parameter is deferent
  • Return type can be same or different in method overloading. But you must have to  change the parameter.

Example:

Method overriding:

  • Method overriding occurs in two Classes that have Is-A (inheritance) relationships.
  • In Case of method overriding, parameter must be same.
  • Return Type must be same

Example:

 

Importance of Finally?

Finally block that used to execute important code such as closing connection, stream etc

Example:

Difference between public, private, protect?

 

Xamarin.Forms CarouselView with image indicators

Download source code

Most of us when we are very familiar with Bootstrap carousel, we expect the same output in mobile CarouselView either. But the problem with Xamarin.Form CarouselView doesn’t provide us such CarouselView with Image Indicators. 

So this article will help the crazy professionals

Step1: Create a Mobile App (Xamarin.forms) project

Open Visual Studio 2017    File    New    Project    Choose Cross-Platform template    choose Mobile App (Xamarin.Forms)    Name it as CarouselViewApp    Click on OK    choose .Net Standard    Click OK

 

Step2: Install CarouselView NuGet Package

Right click on CarouselViewApp    Manage NuGet Packages    type CarouselView.FormsPlugin and Install the package

 

Step3: Create a Model for Images as ImageModel.cs

Before that add the images in CarouselViewApp.Android    Resource    drawable

File: ImageModel.cs

 

Step4: Create ViewModel for MainPage.xaml

Right click on CarouselViewApp    Add    NewItem    Visual C#    Add new class MainPageViewModel.cs

File: MainPageViewModel.cs

 

Step5:  Adding namespace in the MainPage.xaml

 

Step6: Assign BindingContext for MainPage.xaml.cs

File: MainPage.xaml.cs

 

Step7: Creating UI for MainPage.xaml

File: MainPage.xaml

  1. By using Image.GestureRecognizers, we are firing click events using MVVM Architecture
  2. Rotation property for ListView helps us to set or get the current rotation of the element. Here we are rotating ListView to 270 deg
  3. Here the indicators row in Grid is build using RelativeLayout.
  4. RelativeLayout is used here to turn the ListView in Horizontal Direction
    1. At first we move ListView into RelativeLayout, and maintaining the RelativeLayout HeightRequest.
    2. Now we need to fit the ListView in RelativeLayout bounds, this we can do it by using RelativeLayout Constraints.
    3. RelativeLayout.XConstraint, RelativeLayout.YContraint  are used to fix the x,y positions. And then RelativeLayout.WidthConstraint is to set the width for image, RelativeLayout.HeightContraint is to set the height for image.
    4. And the final step is to rotate the ContentView. This will first rotate the cell and the fit image into it.

 

output: Now run the application

  

Authentication and Authorization in ASP.NET Web API using Custom Filters

  • Web API is a platform for building RESTful applications on DotNet Framework. 
  • These API’s can be consumed from Console, Windows, Web, Mobile Applications.
  • As Web API is a part of core ASP.NET, it can be created on either MVC applications, or any other web applications.
  • Web API’s uses all the HTTP features like Request and Response headers, caching and so on…
  • Web API’s can return the data in various formats like
    • string format
    • Json format
    • XML format
    • BSON format

Step 1: Create a  ASP.NET Web API application

Open Visual Studio –> File –> New –> Project –> choose template Web –> click on ASP.NET Web Application  and provide name of the application–> choose Web API from the below check boxes –> Click OK

Step 2: Create a Model and inherit GenericIdentity from Security.Principal assembly

File: UserModel.cs

 

Step 3: Now add a new class for Creating custom filter as MyAuthorization and inherit AuthorizationFilterAttribute and add the following assemblies MyAuthorization class.

File: MyAuthorization.cs

 

Step 4: Here is your CustomAuthorization Filter MyAutorization

 

Step 5: Now create an API Controller and add your custom filter. Here I’m adding for only one method for testing you can add it for the entire class or add it globally.

File: Global.asax 

Add the below line in Application_Start( ), this registers our custom Filter for the entire application.

 File: EmployeeAPIController.cs

 

Step 6: Now create your GUI and on a button click write a server side method. Form this method you can communicate with API. In my case I took a console application.

  1. If you run the web project you will get your local host URL, in my case it was http://localhost:58100/
  2. Here in the authorization Header I have added my username and password in the given format username:password and encoding it to Base64 so that it provides security.
  3. If you don’t pass valid credentials from here, in the method OnAuthorization it should add Unauthorized Response.

 

Step 7: Create console / windows/ web application to consume the API

Here I’ve created Console application.

File: Program.cs

  • Here HTTPClient is used to consume RESTful API’s.
  • And then creating the Authorization header to pass the username and password in format (username: password).
  • client.GetAsync consumes the API and returns the Result.
  • From the result we can check the Status Code.

 

Angular 4 Directives – Lesson 3.3

3.2 Attribute Directives

Here directive is just a class with decorator @Directive and this allows us to specify the directive’s selector.

  • Using custom attribute directive we can change the color, back-ground, font-size etc., of the HTML host element by using ElementRef
  • Renderer class is a built-in service that provides an abstraction for UI rendering manipulations.

Let’s create a custom attribute directive “ShowAlert

Step 1: Create a folder and name it as CustomDirective: /src/app/CustomDirective

Step 2: Now create a typescript file to create your own attribute directive under the associated folder created. And then import Directive, ElementRef, HostListener, Renderer from @angular/core library.

Step 3: And provide your selector name, here I’ve named it as ShowAlert, and create a class that make this directive visible to the component i.e.,add export before the class.

File: app.myDirective.ts

Step 4: Now define contructor for FirstAttrDirective class, and define the style and events using renderer.

For setting up styles,

Renderer.setElementStyle(rendererElement:any, styleName: string, styleValue: string)

(or)

ElementRef.nativeElement.style

For creating events,

Renderer.listen(parentElement: any, name: string, callBack: function)

Step 5: Create your component

File: app.component.ts

Step 6: Add component and Directive in the declaration[ ] of the NgModule  i.e., AppModule

Step 7:  Create a main.ts to bootstrap the NgModule

Step 8: Create a HTML file in /src/

File: CustomDirective.html

Refer required scripts shim.min.js, zone.js, system.src.js, system.config.js and refer the main.js from CustomDirective folder

Output: Default color will be blue, on mouseover font size get increased and changes its color to red, on mouseout will change color to blue and decrease its font size.

Tadaaaa.. 🙂

Angular 4 Directives- Lesson 3.2

Hi friends, in the last session we have learned about built-in directives (ngIf, ngFor, ngSwitch). In this session we will learn,

  • Style and Class Directives ( ngClass, ngStyle)

ngClass:

  • It is used to add and remove CSS classes on an HTML element.
  • CSS Classes can be added in several ways
  1. Using string
  2. Using array
  3. Using object
  4. Using Component methods
  • When using ngClass with object, classes will be added and removed based on the Boolean value that returned.
  • If the value of expression istrue then respective CSS class will be added otherwise that CSS class will be removed from HTML element at run time.

Using String: When using string format, class names must be presented between single quotes with in double quotes “‘class1′” and multiple classes can be separated by space.

File: template.html

File: app.component.ts

Adding styles for the respective classes in component

ngClass using array: When using Array format, each ngClass array item (i.e.,class) must be presented in the string format.

Ex: [ngClass] =”[‘class1′,’class2’]”

File: template.html

ngClass using object: When using object, classes will be formatted in the form of object i.e., each class will be of key and value pairs.

Key: css class name

Value: expression that returns Boolean value

In component file add styles for the respective classes

Using Component Methods: Whereas when using component methods, instead declaring styles statically here styles will be dynamically rendered into template by calling component methods.

  • Depending upon the need/requirement we can pass parameters to the component methods and can dynamically get the required styles.

Ex: [ngClass]=”GetStyles( )”

File: template.html

File: app.component.ts

ngStyle: This directive is used to modify the elements / component styles

  • It accepts an object which defines the elements styles.
  • Both kebab case and lower camel case can be used when specifying style properties.
  • Flexible to add and remove style properties.

File: template.html

File: app.component.ts

JSX Expressions

  • Overview of JSX
  • Creating HTML/XML elements/nodes with JSX
  • JSX Attributes / props
  • Comments in JSX
  • Expressions with
    • Arithmetic operators
    • Ternary Operators
    • Comparison Operators
    • Assignment Operators

Overview of JSX

  1. The full-form of JSX is Javascript and XML, e., simply JSX = Javascript + XML/HTML
  2. JSX is a simple syntax with a combination of HTML/XML tags with Javascript
  3. React used JavaScript expressions within curly braces “{ <expression> }”. We can put any type of JavaScript expression in the curly braces inside JSX.
  4. React can perform only one-way binding, to perform two-way binding we need to use React component’s state and props/ Event listeners.
  5. Each React Element is like a real kind of javascript object which can be either stored in a variable or can be used throughout the program.
  6. After coding in JSX pages no need to precompile the code, the JSX file will be automatically compiled and generates JavaScript syntax in the browser if the JSX is written in ES5, but if the JSX is written in ES6 then this should be pre-compiled by either Babel/ Typescript e.,
    1. Babel
      1. Babel is a process that transforms your JSX code (ES6) into Javascript (ES5) which is browser understandable code.
      2. Bable engine abstracts the Reacts ES6 JSX syntax and recreates that into ES5 syntax, for exampleCode written in ES6 syntax

        Now Babel converts it into ES5 syntax as follows
      3. We will install the following dev dependencies:
        1. babel-loader: babel module loader
        2. babel-core: the core transpiler used for transporting ES2015 and JSX code
        3. babel-preset-es2015: ES6/ES2015 support
        4. babel-preset-react: React/JSX support
        5. babel-preset-stage-2: babel preset for some extra features such as destructuring
        6. webpack: for bundling our packages for distribution and managing dependencies
        7. webpack-dev-server: our development server
      4. Babel 6 doesn’t supports the bundle.js to transform the ES6 to ES5, so for that we need to use Babel older version (i.e., 5.8.X) to transform the JSX code to be pre-compiled and generates the javascript and saved into bundle.js (this can be renamed, and this code is rendered int0 browser) by using webpack.config.js.
    2. Typescript
      1. Typescript is a language the can be either written in ES5/ ES6. Typescript has its own compiler tsc(typescript compiler) to pre-compile the ES6 syntax to ES5.
      2. We will install the following dev dependencies:
        1. ts-loader: typescript module loader to build .tsx
        2. typescript: language for programming in react (either in ES5/ ES6 syntax)
        3. webpack: for bundling our packages for distribution and managing dependencies
        4. webpack-dev-server: our development server
        5. This also uses the bundle.js where after compiling will be saved here with ES5 syntax.
        6. React with Typescript will be written in special extension files i.e., .tsx.               Ex: sample.tsx
  7. Within a JSX syntax we can perform both Data-Binding and Event Binding.

 

Creating HTML/XML Elements/nodes in JSX:

For creating HTML/XML nodes in JSX React provides a pre-defined function.

Syntax:

Where type, props and children are the arguments for function React.createElement( ).

  1. Type (string / React.createClass( ) ):   This is a mandatory argument. Type argument can be a string value (or) it can be a ReactComponent instance.
  1. Props (null / object):   This is an optional argument, where we can pass null (or) an object
  1. Children (null / string / React.createClass( ) / React.createElement( ) ):  This is an optional argument, we can either pass null value (or)  string value (or) React.createElement (or)  React.createClass instance.

 

ReactDOM.render( ):  For rendering react nodes into DOM, React provides function ReactDOM.render( )  from “react-dom” module.

  1. Rendering in react is also possible on server-side withrenderToString( ).
  2. If a change is made (or) a new child nodes has been added to DOM element, ReactDOM will only update the child nodes which is called Re-Rendering.

Ex: Creating <ul> tag with nested <li> tags

 

JSX Props: We have already know the syntax for creating custom HTML elements, second parameter props can be passed as an object/null.

  1. Props are nothing but HTML attributes that are passed as name-value pairs.
  2. Props are generally used for passing inputs to the component.
  3. Props can be passed to nodes in a Component (or) directly to the Component.
    1. Props that are used for nodes/elements are called Node Props/Attributes.
    2. Props that are used for Components are called Component Props/Attributes.
  4. Props creating may vary when using Typescript with React (TSX) with Formal React (JSX). When using TSX must define the type of the Props when creating nodes.

 

Using Typescript with React (TSX)

 

Comments in JSX:

  • Comments in jsx use //  and /* */

Ex:

 

Javascript Expressions:

To make use of Javascript statements with JSX, React provides a syntax using curly braces “{  }”.

Note: Follow the steps for setup ASP.NET MVC application in React Introduction.

Example:

Step1: Open your ASP.NET MVC application à  src/expressions.tsx (Creating file expressions.tsx in src )

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

File: expressions.tsx

File: index.cshtml

File: webpack.config.js

Change the entry point to expressions.tsx

Output:

Sum of 2+3 = 5

 

JSX Expression with Arithmetic Operators:

File: src/expressions.tsx

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

 

JSX Expression with Ternary Operators:

Javascript Ternary Operators ( ? : ) returns two expression depending on condition

Ex:

var a = true;

var result = a == true ?’yes’ : ‘no’;

File: expressions.tsx

Modify the render( ) as follows

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

 

JSX Expression with Comparison Operators

Comparison operators are used to compare any two values / variables

List of the comparison operators

 

 

JSX Expression with Assignment Operators:

Assignment operators just assigns the value to a variable.

Ex:

 

Complete Example

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

 

Angular 4 Directives – Lesson 3

Hi friends, in the last session we have learnt about how to setup in the local environment. In this session we will learn about Directives. Topics that are going to be covered in this session are

  1. Structural directives (Built-in Directives (ngIF, ngFor, ngSwitch)
  2. Style and Class Directives ( ngClass, ngStyle)
  3. Attribute directives
  4. Host Listener and Host Binding

 

Overview of Directives:

Directives are the classes that can change the behaviour or appearance of the components by using CSS Classes, CSS Styles and events.

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements.
  3. Attribute directives—change the appearance or behavior of an element.

Components are the most common of the three directives. You saw a component for the first time in the QuickStart example.

Structural Directives change the structure of the view. Two examples are NgFor and NgIf in the Template Syntax page.

  • We use (*) before the structural directives, and when we use (*) before ngIf/ ngFor, angular actually recognizes that the current element as a template and it will read the current elements as <ng-template>. Where as in Angular 2.X it reads as <template>.

Attribute directives are used as attributes of elements. The built-in NgStyle directive in the Template Syntax page, for example, can change several element styles at the same time.

 

*ngIf:  This directive is used for conditional check on the HTML targeting elements. This will work similar to ng-if in Angular 1.X, where the elements will not get rendered into DOM until the condition satisfies. 

Step1: From the quick start example edit the component.ts

File: app.component.ts

Step2: Create a template.html in the app folder

File: template.html

Note: when use * before ngIf, angular treats it as <ng-template>

 

*ngIf else:  Angular 4  *ngIf has if/else syntax that make sense when you are making ajax calls we can show loading within the page. Where as else block is not existed in Angular 2.

From the above example, add the following html in the template

File: template.html

Angular compiler (JIT or AOT) transforms any <ng-template> elements and directives used with an asterisk (*) into views that are separate from the root component view.

Here when we use (*) before ngIF, angular actually recognizes that the current element as a template, and angular reads it as,

 

*ngIf then else: *ngIf directive can use two templates, one for If condition and the other for else condition. In the previous example we have seen using template for else condition, now for If condition we need to use then statement.

File: template.html

 

*ngFor: *ngFor directive is used to iterate through each element of any array, it works similar to For Loop in JavaScript, where in JavaScript we will write for loop within the <script> tag, but in angular we use *ngFor in the HTML as directive for any kind of elements.

From the above example add the following code in the component file

File: app.component.ts

File: template.html

Here we are using for..of, where

  1. for..of iterates through items and returns values
  2. for..in iterates through properties and  returns list of keys
  3. let is a keyword which is a dynamic datatype of ECMA script.
  4. emp is a temporary variable that hold the current employee from the employees array.
  5. employees is the array of items

Here the let can also create a index as a reference of the current item.

Here index is a built-in keyword of angular framework which can be used in *ngFor. Where angular renders the above code as follows.

 

*ngFor with select tag:

(or)

ngSwitch: ngSwitch works similarly the switch statement that we use in C# / java etc., Here for defining case we use *ngSwitchCase and for default case we use *ngSwitchDefault

From the above example using the same list of employees, we have created a example