Saturday, 30 December 2017

*ngFor in angular 2

 In angular 2 by using the *ngFor we can create the template(nothing but the elements or HTML tags ) building based on the collection count dynamically.
In simple, I can say the repetition of the template creation can be done by using the *ngFor.

Syntax:
<tagname *ngFor="let x of arrayofobject/array">
{{x.property/x}}
</tagname>
By using the ngFor we can do the repetition for both the array and the collection of the array of the

Tuesday, 26 December 2017

Validations In Angular JS

Angular provided us some of the directives that which will be helpful for the validations over the form while submitting. Not to forgot that, as angular is dealing from the client side it will not fulfill the requirement of validation in the case if user turn off/disable the javascript on the browser where the application is running.
Before going to implementation of the validations, lets go through with the following angular properties which are related to find the sate/behavior of the form.
   a)ng-valid : $valid property states that the validation rules are true over the element. The return type of the $valid is boolean which can be true or false.

b)ng-invalid : $invalid property states that the validation rule over the element are false. Here too the return type of the $invalid is boolean which can be true or false.

c)ng-pristine : $pristine states that fields in the form are not yet modified if the result is true, else viceversa.

d)ng-dirty : $dirty states that some of the fields in the form has been modified if the result is true or else viceversa.

e)ng-submitted : $submitted states that the form was submitted.

Angular also provided us the directives which can be identify the state( likely modified or not) of the input tags.

a)ng-valid : The $valid states that the input field with data is valid.

b)ng-invalid : The $invalid states that the input field with the data was invalid or not met the needs of the field.

c)ng-untouched : The $untouched property states that the concern input field was not touched at all.

d)ng-touched : The $touched property states that the concern input field was disturbed by user inputs.

e)ng-pristine : same as for the form, this states that the field was not yet modified.

f)ng-dirty : similar to the use in form level, here too states that the input field was modified.

In this article lets accomplish the validations based on some of the regular usage of requirements as follows :

a)      Disable submit button until user enter the value in textbox :
<form name="myForm">            
Username:<input type="text" name="user" ng-model="usernm" required> <br /><br />
<button type="submit" ng-disabled="myForm.user.$invalid">Submit</button>          
</form>
Result :


In the above HTML lines if we observe, I had used the ng-disabled directive which is used to disable the tag/element based on the expression provided to it. I had given the expression as the “myform.user.$invalid”, Here “myForm” is name of form. “user” is the name of the input. Make sure to provide the required attribute which belongs to HTML5.
 b)Display message if user disturbs the input text and make empty even though it’s mandatory:
<form name="myForm" >                   
            Username:<input type="text" name="user" ng-model="usernm" required>
                <span style="color: red" ng-show="myForm.user.$dirty">
                <span ng-show="myForm.user.$error.required">Username is required.</span>
                </span><br /><br />  
         <button type="submit" ng-disabled="myForm.user.$invalid">Submit</button>
    </form>
Result :


In the above markup snippet, It shows the span by usinng the ng-show expression. Here the expression “myform.user.$dirty” becomes true if the user disturbs(means like writing text or cleaning the existing text in field) the input field.
In the second span too I had used the ng-show with expression as like “myform.user.$errer.required”, it behaves based on the required attribute of the input tag.
   C)Email Validation :
<form name="myForm" >                   
    Email : <input type="email" id="txtmailid" ng-model="useremail" name="txtmailnm" />
    <span ng-show="myForm.txtmailnm.$touched && myForm.txtmailnm.$error.email">Please enter valid email id.</span><br /><br />
    <button type="submit" ng-disabled="myForm.user.$invalid">Submit</button>   
 </form>
Result :


The error message was binded in the span tag which will be shown based on the the expression provided to it to the attribute ng-show. The condition becomes true when the $touched sets to true(becomes true when user focus the tetbox ) and email input which give to the textbox of type email.

D)Dropdownlist validation :
<form name="myForm" >                   
    <select id="dept" name="depts" ng-model="seldept" required>
        <option value="">--select--</option>
        <option value="1">Developer</option>
        <option value="2">Architect</option>
        <option value="3">Tester</option>
        <option value="4">Desigener</option>       
    </select>
         <button type="submit" ng-disabled="myForm.depts.$invalid">Submit</button>   
 </form>

 Result :

Here too, my button tag will be in disabled mode until it validates the condition “myForm.depts.$invalid” with false. Here, ng-model and required attributes are mandatory to be set the validation, Where ng-model is the angular attribute and the required is the feature of HTML5.
    E)Button disabling if radiobutton not selected :
<form name="myForm" >                   
    Gender:
     <input type="radio" name="gender" ng-model="gen" value="male" required />Male
     <input type="radio" name="gender" ng-model="gen" value="female" required/>Female
     <br />
    <button type="submit" ng-disabled="myForm.gender.$invalid">Submit</button>   
 </form>
Result :


As like above cases here also, we are disabling the button untill the user selects the radiobutton by providing the exression as “myForm.gender.$invalid” . we have to make sure of providing the ng-model attribute for radio type tags.

Generating error message on button click :

This scenario is just like verifying weather our form is valid or not on clicking the submit button.So, provide a name attribute to our form as like below example and check the conditions based on our need. 
<form name="form" ng-app novalidate>
  <div class="form-group">
    <input name="first_name"
          type="text"         
          ng-model="firstnamemodel"          
          required />
  </div>
  <div ng-show="submitted && form.$invalid">
  <div ng-show="form.first_name.$error.required">
    First Name is Required
  </div>
</div>
  <button
    type="submit"   
    ng-click="submitted=true">
      Submit
  </button>

</form>

Result :



In angular we can create our own custom directives which can be used as mark up tag. So, By using the custom directives we can create a tag/attribute of input type which behaves to accept only numbers or alphabets whatever according to our requirement. In my next article I'll discuss about some regularly using custom directives.

Saturday, 23 December 2017

Property Binding, Interpolation and Click event handler

In this page, lets go with the things like making/using the button click event and retrieving the data from the class.
a)Property binding :
Property binding is nothing but attaching the property value(from our ts class) to the attribute of the HTML tag. Every HTML tag will be containing the attributes. For example if we take input tag like textbox, then we can have attributes like id,name..e.t.c.
How to define the property binding ?
To bind and get the property value of a class to the attribute, firstly we need to decorate the attribute with in the open and close square brackets (  [attribute] = 'propertyname' ).

Example :

 @Component({  
  selector: 'app-root',  
  template : `<button [disabled]='btnDisabled' > Disabled </button>  
        <button [disabled]='!btnDisabled'>! Disabled </button> `   
 })  
 export class AppComponent {   
  btnDisabled : boolean = true;  
 }  

Explanation :
1)In the above example, I had taken a class “ApComponent” and added a property named isDisabled.
2)within the template of the decorater I had taken 2 HTML button tags.
3)For the both button attributes, I had attached the btnDisabled property by decorating with the open and close brackets.

Result :

b)Interpolation :
Interpolation also provides us a way for binding the property values, to make interpolation we need to enclose the property value within the double open and close curly braces ( {{ propertyname }} ).
To know about interpolation, Please have a look on my page :
Then what makes the differences between property binding and interpolation ?
Let us try to apply interpolation for the above example :

 import { Component } from '@angular/core';  
 @Component({  
  selector: 'app-root',  
  template : `with property binding : <br/>  
        <button [disabled]='btnDisabled' > Disabled </button>         
        <button [disabled]='!btnDisabled'>! Disabled </button><br/><br/>  
        With Interpolation : <br/>      
        <button disabled={{btnDisabled}} > Disabled </button>         
        <button disabled={{!btnDisabled}}>! Disabled </button>     
        `   
 })  
 export class AppComponent {   
  btnDisabled : boolean = true;  
 }  


Result :
Explanation :
In the above example, to make differences between the interpolation and the property binding I had used both(interpolation & property binding) in the template. For the first two button tags I had used the property binding and for the next two button tags I had used the interpolation.
If you observe the result, The differences can be clearly identified. The interpolation used buttons both are in disabled mode.
Even though I had provided the not disabled {{ ! btnDisabled }} inside the interpolation, It is behaving in disabled mode itself.

Confused about Which one to prefer  ? 
If your property value is plain string value then go for interpolation {{ plaintext/string  }}.  
If your property value is other than string format, then better to choose the property binding.

Binding Click handler :
Here lets know about creation and using the click event over a button control.
In angular 2, to handle the click event, we need to attach the handler by making the attribute “click” within the open and close parenthesis  ( (click) ) And then we need to attach the function name as the value to the attribute ( (clcik)=’functionname()’ ) . The function name needs to be declared within the class of the component.

Example :

 import { Component } from '@angular/core';  
 @Component({  
  selector: 'app-root',  
  template: `count : <span>{{count}}</span><br/>  
        <button id='btn' (click)='Increment()'>Count + 1</button>`  
 })  
 export class AppComponent {  
  title = 'app';  
  //count :any = 0; //property can be of any type allowed  
  //count = 0; //allowed  
  count : number=0;  //number type allowed  
  Increment() {  
   this.count=this.count+1;  
  }  
 }  

Explanation :
In the above  example, within the template I had used the button tag with click handler by assigning the function named “Increment()”.
Within the class “AppComponent” I had taken the property named count of type number.
The function “Increment()” I had declared within the “AppComponent” Class, will increment the property “count” value whenever we click on the button.

Result :

Thank you.




Tuesday, 19 December 2017

A basic "Search Me" game in javascript

Search me is a game based on keywords like search,time and puzzle. This is a simple game where the user will face a 10 letter word and From that word, the user needs to search letter by letter in the given shuffled letters in matrix format with the given time. The user will earn 10 plus points for finding out the each letter.
To accomplish this, I had used only javascript code.
Algorithm I followed with text : 
1) Initially I thought about the 10 letter word displaying to user which he needs to find out and also making the first letter to be with highlighted color(whcih the usrer needs to find). For this I had taken

Monday, 18 December 2017

Interpolation In Angular 2

In general, Interpolation means injecting something within a process which is happening.
If we compare to our work: Here, we are injecting/transferring  the data from the typescript(component.ts) to the view(means our HTML file) like our template or templateurl. To define the interpolation we have to use the double curly braces{{}}. Within the curly braces we need to provide the properties that which we had declared or can be initialized as like {{propertyname}}. Internally, our angular translates the interpolation into property and fetches the related property value from the class and

Friday, 15 December 2017

First Component Creation in angular 2


In angular 2, a component plays a key role while building the UI block and its business logic and for more features. In this article lets go with creation of our own component and it's execution.
Note : By the below three points we’ll get the structured project of our angular application which I had discussed in detail in the followed link(Creating First angular 2 aplication). Here just as to rewind the things I’m speaking with the following 2 points.
1)Initially, let us create our application folder(I created folderr with nameDemoFive).

Monday, 11 December 2017

Component and Execution mapping


Unlike to angular js 1.x which is module based, Angular2.0 was component based framework. So, in this article let’s dig over the concept “Component”.
What is component ?
In simple terms, I can say that a component is nothing but the place we provide our business rules(inside a class), user interface(likely Presentation layer) information and related styles information as a group together.In the comparison words with angular js 1.x version the components are like directives.
In angular 2, after having our application structure by using “ng new appname” our angular cli will

Saturday, 9 December 2017

Prerequisite & First Angular 2 App

Introduction to Angular 2.0
Angular 2.0 mainly focused on the following points :
  • Removal of most of the modules for resulting better performance
  • Google focused on mobile development with better performance.
  • Angular 1.0 is a module based framework.
  • Angular 2.0 is a component based framework.
  • Removal of controllers and $scope had been taken place in this version.
  • Angular 2.0 is dependent on the typescript language.
  • The components in this framework is over or against to the controllers to the earlier version.
  • Note came from the angular is that this updated framework is meant for the better result in

Friday, 1 December 2017

Routing In Angular JS

Routing is like having/viewing an another view(which we need) which is based on the requested URL internally, within a view(current). In simple without any kind of reloading injecting a child page within the parent page. By using this angular ng-routing we can make our application to behave as like single page applications(SPA’s).

Flow of routing / How it process ?:

Wednesday, 29 November 2017

Basic Game : 4 x 4 Matrix puzzle by using Javascript and Jquery


In this article I had planned with a number puzzle game of 4 x 4 matrix. Here I'm working by using javascript and Jquery. In my upcoming articles I'll go with angular too definitely.
All the code I did is just based on my written algorithm or  views. We can even reduce the code that what I done with, I welcome all the code reduce inputs in comment section.
you can test the code by copying and pasting in the below link of try it editor.

Saturday, 25 November 2017

Angular Basic Interview Questions Set-3

<< Previous Questions with Answers

21)what is $on ?
$on function in angular is used to listen the event that has been triggered.It listens the events that are triggered by using $broadcast and $emit functions.$on is one of the function of $scope which can be initialized like $scope.$on
syntax :
app.controller('ctrlname', function($scope){
  $scope.$on('emitorbroadcast', function(){    
   //our code
  })
});

22)How can you create your own directive ?
By using custom directives we can create our own directives with certain behavior adding to it. That created directive can be used as an markup element in our view.
syntax:
myApp.directive(‘ourdirective’, function() {
    return {
        restrict: ‘E’,
        template: ‘<h1>I made a directive!</h1>’
    };
});
Using in view :
<ourdirective> </ourdirective>

23)What is link ?
While bootstraping the angular, the compiler cant get perform actions over the scope members. To get start working over them it should pass over the link phase where the scope values get initialised, ofcourse we get the compile phase before getting to this step but the instance of our directives template will gets generated at link itself.If we define the link key with its function as value then it executes as like the post-link by default.

24)What is compile ?
In the process of bootstrap, the parser gets hit to the $compile function where this function grabs all the templates related to the directives. At this phase we cant play with the scope for the templates as the instance will not be created.The compile phase will gets compiled only once for the template and the impact of its logic will apply to all created instances later.The return type of the compile phase will be as pre and post functions.

25)What is the order of execution between pre, post and compile ?
  • Initially, the compile phase will gets executed which returs pre/post functions.
  • After compile phase getting executed, the pre-link will execute.
  • As soon as the pre-link executed goes to the post functions execution flows from bottom-top trace over the custom directive concern template.

26)What is pre ?
In pre-link function we won't get access towards the child elements which we careated by the directives.In some cases we may have to use the parent and child elements as custom directives. At that situation for some of the child elements(created via directive) scope values can make enable at the pre-link function itself as they execute firstly then moves to post while parsing. 

27)What is post ?
Post function in the custom directives is mostly preferrred place to write any kind of logic over the template as the parent & child, both elements with its template related instance and scope will be available.
For more details related to the pre and post find in the followed link :

28)What is restrict ?
Restrict is used as one of the key in the custom directives. By using this key we can make or set the behavior of our directive which we are creating. The restrict can be of four modes as follows :

E - Restrict with value as "E" will behaves as an element in our view.
A - Restrict with values as "A" will behaves as an attribute for an element in our view.
C - Restrict with values as "C" will acts as a class for an element.
M - Restrict with values as "M" will acts as a comment.

29)Does angular allows nested controllers using ?
Yes, we can also use the nested controllers based on the requirement.

30)Can we go for $watch in the compile phase ?
No, as compile is the initial phase over the directive, It just creates the template for the directive while parsing over the DOM. So, we can't access the scope members. We can play over $watch in the post function.

Wednesday, 22 November 2017

Custom Directives in Angular JS Part-2

    If you are new to custom directives creation please have a look of part-1 of this series in the followed link Custom Directives Part-1
In this part-2 lets discuss related to the concepts of compile & link keys using in custom directives.
Compile key in Custom Directive :
In general,for every directive there will be a compilation phase. This phase comes whenever the angular parser faces the directive for the element while parsing. pro grammatically this