Skip to main content
Angular 2

https://www.youtube.com/watch?v=WWQZCDegWHg
https://www.youtube.com/watch?v=H9iK2Eib85E
https://www.youtube.com/watch?v=WWQZCDegWHg&list=PL6n9fhu94yhWqGD8BuKuX-VTKqlNBj-m6

>> Angular 1 release?
October 2010

>> Angular 2 release?
May 2016

>> Angular 4 release?
March 2017
The plan is to release a major version every six months, so Angular 5 will show up in September 2017, followed by Angular 6 in March 2018 and Angular 7 in September 2018. Nobody can predict the future, but the idea is for future versions to introduce minimal breaking changes.

>> installation requirement for angular 2?
node version 4.6 or more
npm 3.x.x

>> why to use angular 2 instead we already have angular 1?
Angular 2 is not simple upgradation from angular 1, angular 2 is completely re-writern so lot of improvements as compare to angular 1.
Performance - 
angular 2 is 5 times faster than angular 1. angular 2 has faster initial load, changes detection and improved rendering time. This also improves modularity, dependency injection and testability.
Mobile support - 
Is designed from the group up. In angular 2 we can create single application that can works across mobile and desktop devices. Its possible to use angular 1 for mobile but we need thirdparty frameworks for that.
Component based development - 
In angular 2 everything is component components are the building blocks of an Angular application. The advantage of component based is it facilitates code reuse. for unit testing point of view angular 2 is more unit testable.
More language choices -
We can use any of the mentioned programming language to build the angular 2 application,
ECMAScript 5
ECMAScript 6 (also called EC 2015)
TypeScript
Dart
PureScript
Elm
Among all above languages typeScript is more popular language.
Angular 2 itself is built using typescript. Typescript has great support for ECMAScript 6 standard.

Other notes of angular 2
  • Angular 2 is entirely new framework it does not need knowlege of angular 1.
  • We are using Type script in angular js, Type script is super set of javascript, Any valid type script code is valid type script. which means we dont have to learn new programming language.
  • Type script brings some missing features which are not/missing in current javascript. It supported by most browsers. We get module, classes, Interrfaces, Access modifiers(public, private), intelicent and compile time checking.
  • AngularJs is one of the leading framework, it has huge community support.
  • Building angular js application is gives you single page experience it means that the page contents are get replace without loading page. 
  • Single page application will provide a very fast and fulid experience.
  • Gmail is nice example of single page application.
  • In angular js application is built in modular, maintanable and testable way.
  • Angular js 2 compile time checking happens.
  • Template in angular js look like html but we can use attribute like *ngFor, {{ variableValue }} etc. in it.
>> Difference between angular js, angular 2 and angular 4?
AngularJs 2010
Angular2 2016
Angular4 2017

Difference between angular js and angular 2 - 
  • Angular2 is not a simple upgrade from Angular1.
  • Angular 1 is most popular javascript framework.
  • No need to learn angular 1 to learn angular 2.
  • Angular2 is completely re-writern from the ground up, As a result so way we write angularjs and angular2 is different.
  • AngularJs 1 is revolve on the concept of controllers to glue controller in view angular uses $scope, but in angular2 we both controller and $scope are gone.
  • Angular2 is entirely component based which means we create set of loosely coupled components and put them together an angular 2 application. So components are the building blocks of angular 2 application. The advantages of component based application is that its great for code reuse. e.g. rating component can used on rating page or on product page for rating. 
  • From unit testing point the use of makes an angualr2 application more testable.
  • Angular2 is 5 times faster that angular 1.
  • AngularJs 1 was not build for mobile devices, where angular2 on the other hand is designed from the ground up with mobile support in mind.
  • With angular2 we have more language choices (Javascript, Typescript, Dart, PureScript, Elm etc.)


Difference between angular2 and angular4 - 

  • Changing from angular2 to angular 4 and even future versions of angular, won't be like changing from angular1 it won't be complete rewrite it will simply change in core libraries. For developer stand point building an application using angular2 and angular4 is not very different. we still use the same concepts and patterns. Angular4 is simply next version of angular2 if you learned angular2 then you well prepared to simply use angualr4.
  • Angular4 is backwards compatible with angular4 for most applications.


What has changed and what is new in Angular4 -
  • Some under the hood changes to reduce the size of the AOT(Ahead-of-Time) compiler generated code. Migration to angular4 may reduce to production bundles to hunderds of bytes.
  • In angular4 TypeScript 2.1 and 2.2 compatibility. upuntil angular4 only support typescript 1.8 but now we can use 2.1 or 2.2.
  • Animation features are pulled out of @angular/core and are moved into their own package. This means if you not use animation then this extra code will not be added to your application bunddles.
  • We can now use New if/else style syntax with *ngIf structural directive.


What happened to Angular 3 -
Due to misaliangment of the browser packages version, the team decided go striaght for angular4. (except the angular router libray all the other angular core libraries are versioned the same way. while all the other core package version 2 the router libray is already at version 3).
e.g.
@angular/core          v2.3.0
@angular/compiler      v2.3.0
@angular/compiler.cli  v2.3.0
@angular/http          v2.3.0
@angular/router        v3.3.0

Naming guidelines to describe Angular versions -
  • Use "AngularJs" to describe version 1.x or earlier.
  • Use "Angular" for versions 2.0.0 and later.
  • Use the version numbers "Angular 4.0", "Angular 2.4" when you need to talk about specific release. Otherwise it is just inough to descript using "Angular".



>> What is ECMAScript?

  • The javascript standard is officially known as ECMAScript.
  • Most modern browsers available are supports ECMAScript 5.
  • The browser supports for ECMAScript 6 is still in complete.
  • A process called "Transpilation" compiles ECMAScript 6 to ECMAScript 5. 
  • ECMAScript 6 is known as ECMA 2015 it has new features like Classes, Modules, Arrow functions etc.
  • (ECMAScript "European Computer Manufacturers Association Script" is a trademarked scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript, so as to foster multiple independent implementations.)



>> What is typescript?

  • Is free and open-source programming language developed by Microsoft.
  • It is super set of Javascript.
  • The process called "Transpilation" compiles TypeScript to JavaScript.
  • when we use TypeScript for building angular js application it provides bellow benefits,
  • Intellisense 
  • Autocompilation
  • Code navigation
  • Advanced refactoring
  • Strong typing
  • Supports ECMA 2015


>> TypeScript is supported by various code editors?

  • Visual studio
  • Visual studio code
  • Eclipse
  • WebStorm
  • Atom
  • Sublime Text




>> Building blocks of AngularJs 2?
We have 4 key players or building blocks in angular 2,

  • Components
  • Directives
  • Routers
  • Services



Component -

  • Encapsulates template, data and behaviour of the view. So it more accurate to call it view component.
  • Every Angular 2 app which has atleast 1 component which is called root component. In real word an application offen consists of multiple components.
  • Each component has template or html markup for the view as well as data and logic behind that view.
  • Components can also contains other components. The benefit of this architecture style is help break up large application into various complex views into smaller more managable components or view component. plus we can reuse this componet in different parts of application or even in different application. 
  • Even though tag/html element is loaded angular js is not able to recognised wheather the tag is related to specific component or not, even though we have defined component in our application no where we have referenced it.
  • Angular does not scan all your files to discover your components. it will only recognise the component that you have explicitly referenced. So referenced can be achieve using "directives" attribute in component annotation, here we can mention directives or components inside current component.

e.g. 3 different component for
Navbar
Sidebar
Courses/content


  • These components are decouple from the DOM. This is because these make components unit testable.
  • In plain JavaScript or jquery we get reference to DOM element in order to modify or handle its events. 
  • In angular instead of reference of DOM element we use binding so that in view we bind view to properties and method of component. 
  • If there is any change in valuable property the DOM element bound to this property will refresh automatically we do not need to press the key f5 to refresh page (this is browser sync which is node module that are Lite web server uses). 
  • So we cant and shouldn't get reference to that DOM element in order to update it. 
  • Similary to handle an event raise from DOM element we bind an element like click to method in component when user clicks on that element the cresponding method in component will get called.
  • A component nothing but plain type script class it can have properties and methods. These property can hold data for view and methods implement the behaviour of the view.
  • components encapsulates data and logic behind view using property and function in component.
  • When we need to add multiple line inline html in component template we can use backtick character "`" (before 1 in keboard) and write multiline html code. 

e.g.
export class RatingComponent {
  averageRating: number;
  setRating(value) {
  ...
  }
}

Some time we need to talk to back-end APIs to get or save data. To have good separation of cencerns in our applications we delegate any logic that is not related to view to a service.

Service -
Its as plain class that encapsulate any non user interface logic like making http calls, logging, businsess roles and so on.

Router -
Is purely resonsible for navigation so user navigates from one page to another it will figure out based on changes in url what component to present to the user.


Directive - 

  • We use directives to extend or control document object model we can define custom attributes or custom element that are not part of html. We can add another component as referenced in directive,  it means that technically every component is directive with difference in component has template but directive does not have template.
  • Similar to component we use directives to work with DOM, but directive unlike component doesn't have the template or HTML markup review.
  • We often use it to add behaviour to existing DOM elements.
  • We can have bunch of directive for,
  • Adding or removing DOM elements.
  • Adding classes or styles to them
  • Repeating them.
  • We can also create our own custom directives.



>> Installing Angular Js 2
we need npm or node package manger for managing dependencies of our application.
$ npm install -g typescript // this will install typescript on globally
After this we need editor like,
    vs code
    sublime
    Adam
    Intelli J
    vidual studo
    or any other editor to support type script.
To install angular js We can use angular command line interface or cli,
$ npm install -g angular-cli
$ npm new project_name
$ ng serve
$ npm start

>> Folder structure of angular Js 2,
app
-- app.component.ts // this is root component of application
-- boot.ts // main or starting module of application
index.html
package.json // standard node configuration file
tsconfig.json // configuration file for typescript compiler, so that it used to determine how to compile or more accurately transpile our typescript files into javascript e.g. es5 (current version of javascript)
typings.json // another configuration file for typescript when ever we used external javascript libraries in typescript we need to import typescript definition file this type defination file gives us static type checking and tellisense for that javascript library. e.g. "es6-shim": "github: definiteTyped/Definitely"

In package.json scripts >> start section >> "concurrent \"npm run tsc:w\" \"npm run lite\" "
npm run tsc:w // means run typescript compiler in watch mode
npm run lite // starting lite web server

A tyepscript compiler in watch mode we can modify and save a typescript file and then the type script compiler will automatically generate a Javascript and Javascript map file in the same folder. Javascript file eventually one that will be loaded in the browser but we never have to view or modify it we code purely in typescript.
$ npm start // here in this out typescript compiler is running in watch mode and our lite web server is started this also launches our default browser on machine.

http://localhost:3000 // will run angular js project

>> Typescript compiler operation?
when typescript compiler runs it creates two file per components,
app.component.js
app.component.js.map // this file is used during debugging, if something goes wrong and we try to debug in browser this map file will take us to the corresponding line in your typescript file.


>> root component?
 is typescript file of component, root component is nothing but plain type script class it just decorated with component decorator
e.g. code in file is app.component.ts
import {Component} from 'angular2/core';

//this is decoration or annotation add metadata about the this class, so all the building blocks of the angular 2 apps that talks about type script classes that are decorated with some decorator
@Component({
  selector: 'my-app',
  template: '<h1>My first angular 2 app</h1>'
})

//
export class AppComponent {}


>> Naming convention for component?
In app directory we can create component,
e.g.
nameofpage.component.ts


>> what is export in component?

  • In typescript each file is considered as a module in each module we often export one or more things like class, functions or varibale.
  • Exporting component class so it will be available to other modules in the application. So that if later when needed we can import this class using "import".


>> How does angular know that the class is going to be an component?
It looks for specific attribute or metadata on your classes.

>> Decorator?
Decorator in angular is like an attribute in c-sharp or an annotaion in java many other languages has similar concepts. So decorator are function in angular js which is exported in angular2 core module. To write decorator we need to import the angular2 core component at top of your file.
Selector - 
selector is string in docorator it specifies a CSS for host HTML element. When angular sees the element that matches this CSS selector it will create instance of out component in the host element(element with tag or selector name).
Template -
this specifies HTML that will be inserted into the DOM when the components view is render. we can write template inline or put it in a separate file.
e.g. courses.component.ts
//import component decorator
import {Component} from 'angular2/core';

//call decorator
@Component({
  selector: 'courses',
  template: '<h2>Courses</h1>'
})

//create component
export class CoursesComponent {

}

>> How to add referenced of one component in other component.
We can add/import referenced of one component in other using component annotation attribute "durectives". In directives it need to mention component class name and in file top portion we need to import referenced component using path from current coponent listing.
e.g. app.component.ts

import {Component} from 'angular2/core'; // import component decorator
import {CoursesComponent} from './courses.component'; // referenced of another component using file name without ts extensdion

//call decorator
@Component({
  selector: 'my-app',
  template: '<h1>Angular js 2 app main component</h1><courses></courses>',
  directives: [CoursesComponent] // we need to add reference of cources component in to this main component
})

//create component
export class AppComponent {

}

>> What is interpolation in Angular Js 2?
To render the property/variable value from component to template html we can use "{{ variableName }}" this is called interpolation.

>> One way binding?
value of property in the component changes then the view will automatically refreshed angular will take care of this as we do not have to worry about this is called One way binding.
e.g.
import {Component} from 'angular2/core';
@Component({
  selector: 'courses',
  template: `
            <h1>Courses</h1>
            {{ title }} // this is called interpolation
            `
})

//create component
export class CoursesComponent {
  title = "The title of courses page"; // bind this "title" value in template "{{ title }}" is called one way binding
}


>> Two way binding?
Is used in forms when you type something in input field that is bound to property as you modify the value of input field the property will be updated automatically is called two way binding.


>> Add for loop in angular js 2? How to use *ngFor directive?
We can add forlooping in template using "*ngFor" star ngFor="#course of courses".
e.g.
import {Component} from 'angular2/core';
@Component({
  selector: 'courses',
  template: `
            <h1>Courses</h1>
            {{ title }}
            <ul>
              <li *ngFor="#course of courses">
                {{ course }}
              </li>
            </ul>
            `
})

//create component
export class CoursesComponent {
  title = "The title of courses page";
  courses = ["Course1", "Course2", "Course3"]; // add array varable with values which we can use in for looping in template
}


>> Services in symfony 2?

  • Component will not have any code to get the data from the server it will simply delegate to service.
  • Service is just a plain class nothing more than that.
  • Any logic which was not included in view using component then we can use service for that.
  • Can be create using format in app folder "serviceName.service.ts".

e.g. courses.service.ts
export class CourseService {
    getCourses() : string[] {
        return ["Course1", "Course2", "Course3"];
    }
}
//to import service in component use bellow
import {CourseService} from './course.service'

//use/reference the service function it need to create contructor and pass service class in component use bellow,
// do not use new CourseService() in contructor it is tight coupling not suitable for changes
constructor(courseService: CourseService) { // parameter name to constructor should be camel case
  
}


>> Dependency injection?

  • Angular has built in dependency injection framework.
  • The job of dependency injection framework is to inject dependencies of your classes when you creating them. so when creating course component it looks at the constructor and sees we need a course service. first it will create instance of service then inject it into the constructor of course class this is what we call dependency injection.
  • Angular js will not know which services you are going to use we need to teach/tell it to use specific service using "providers" attribute.
  • To use service in component constructor we need to add service name into component annotation attribute "providers" we can initialize the service in providers attribute.

e.g.
import {Component} from 'angular2/core';
import {CourseService} from './course.service'

@Component({
  selector: 'courses',
  template: `
            <h1>Courses</h1>
            {{ title }}
            <ul>
              <li *ngFor="#course of courses">
                {{ course }}
              </li>
            </ul>
            `,
  providers: [CourseService]
})

export class CoursesComponent {
  title = "The title of courses page";
  courses ;
  constructor(courseService: CourseService) {
    this.courses = courseService.getCourses();
  }
}


>> custom directives?

  • Directive is just a class that has directive decorator we can give selector and then implement logic in it.
  • To use directive in component first import that on top of component then use directive attribute of component annotation and add directive name into it.
  • We can create new file in app folder like "auto-grow.directive.ts" and create class for directive with importing angular2 core directive same as compoent.
  • There are many attributes in annotation of Directive like selector in our case value will be "autoGrow" and then host attribute we can add events in host attribute. Events supplies their handlers using key value pairs "'(focus)': 'onFocus()'", onFocus() is method in our directive class.
  • To add hosts in directives we need to import services in angular js 2 core. like ElementRef(gives access to host element), Renderer(use to modify element). and then create constructor and pass these as arguments in directive constructor.
  • In bellow example "autoGrow" is custom directive, directive will going to apply "autoGrow" attribute for input element.

e.g.
<input autoGrow />

e.g. create custom directive create file auto-grow.directive.ts
import {Directive, ElementRef, Renderer} from 'angular2/core'
@Directive({
    selector: '[autoGrow]',
    host: {
        '(focus)': 'onFocus()', // onFocus() is method in directive
        '(blur)': 'onBlur()'   // onBlur() is method in directive
    }
})
export class AutoGrowDirective {
    constructor(private el: ElementRef, private renderer: Renderer) {
  
    }
    onFocus() {
        this.renderer.setElementStyle(this.el, 'width', '200');
    }
    onBlur() {
        this.renderer.setElementStyle(this.el, 'width', '150');
    }  
}

//use the above directive in component template
import {Component} from 'angular2/core';
import {CourseService} from './course.service'
import {AutoGrowDirective} from './auto-grow.directive'

@Component({
  selector: 'courses',
  template: `
            <h1>Courses</h1>
            {{ title }}
            <input type="text" autoGrow /> // this is custom directive "autoGrow" added
            <ul>
              <li *ngFor="#course of courses">
                {{ course }}
              </li>
            </ul>
            `,
  providers: [CourseService],
  directives: [AutoGrowDirective] // use this to add/include custom directive in this component
})

export class CoursesComponent {
  title = "The title of courses page";
  courses ;
  constructor(courseService: CourseService) {
    this.courses = courseService.getCourses();
  }
}


A component in angular 2 is class with template and decorator. So component is composed of
class
template
decorator

Templates -
defines the user interface, Contains the HTML, directives and data bindings.
we can also run IIS server to run the angular application.
for template we can also use html file,
e.g. app.component.html
<h1> This is my html file to be include in component template {{ name }}</h1>

//in compoent file app.component.ts
import {Component} from "@angular/core"
@Component({
    selector: "my-app",
    templateUrl: "app/app.component.html",
    styles: ['table{color: black; font-size: 13px}', 'td{color: red;}'] // we can also specify styles here
  
    OR
  
    styleUrls: ['employee.component.css', 'main.component.css'] // we can also specify path of css files
})
export class AppComponent {
    name: string = "Angular 2";
}

class - contains the code required for the template.
decorator - adds meta data to the class making it an angular component.


>> what are the options to add/apply style in component?
  • Styles in external stylesheet: style.css
  • Styles inline in the compoent html file
  • Styles in the component html file using <style> tag
  • Specify the styles using the @component decorator styles property.
  • Specify the styles using the @component decorator styleUrls property.



>> AngularJs interpolation?
  • One way data-binding - From Component to View Template. e.g. <img src="{{imageUrl}}" />
  • One way data-binding - From View Template to Component. e.g. <img [src]="imageUrl" />
  • Two way data-binding - From Component to View Template and From View Template to Component.


>> Interpolation and property binding difference?

Interpolation
<img src="{{imageUrl}}" />

Property Binding
<img [src]="imageUrl" />

Interpolation V/S Property Binding
  • Interpolation is a specific syntax that Angular converts into a property binding.
  • To concatinate we must use interpolation instead of propery binding. e.g. <img src="http://example.com/{{imageUrl}}" />
  • To set an element property to a non-string data value, you must use property binding. e.g. <button [disabled]="isDisabled">Click</button>


Property Binding
  • Remember to enclose the property name with a pair of square brackets.
  • Canonical from can be allowed. e.g. <button bind-disabled="isDisabled">Click</button>
  • Angular data binding sanitizes malicious content before displaying it.



>> Angular binding?
Angular binding works with properties and events, and not attributes.

e.g. in bellow example "disabled" is DOM property, and not attribute.
<button [disabled]="isDisabled">Click</button>
<button disabled="{{isDisabled}}">Click</button>


>> Attribute binding?
Angular recommends to property binding when possible and attribute binding only in situation where we do not have corresponding properties that we can bind to. e.g. colspan attribute does not have corresponding property in the DOM.

//Two different ways to implement attribute binding,
e.g. Interpolation type syntax for attribute binding, we use "attr.attributeName" for attribute binding
<th attr.colspan="{{columnSpan}}" >

e.g. Property binding type syntax for attribute binding,  we use "[attr.attributeName]" for attribute binding
<th [attr.colspan]="columnSpan" >


>> DOM execution/tree?
  • HTML attributes and the DOM properties are different things.
  • Interpolation binds class properties to DOM property.
  • Each html element has DOM object with properties.


e.g. Tree of Dom is

                                                    | -> head -> title
window -> document -> html ->
                                                     | -> script
                                                     | -> body ->
                                                     | -> div -> h1                          
                            

  • Basically we can treat DOM(Document Object Model) as an API(Application Programming Interface) for html so that we can use programming languages like javascript or javascript frameworks like angular to access and modify html elements using their corresponding DOM object.
  • DOM contains as html elements as object their property events, methods and it is standard to accessing, modifying, adding, deleting our html element.
  • Keep in mind angular data binding is all about binding to DOM object properties and html element attribute.


Difference between html element and DOM property - 
  • Attributes are defined by HTML, where as properties are defined by the DOM.
  • Attributes initialize DOM properties, Once initialization complete, the attributes job is done.
  • Property values can change, where as attribute values can't.


e.g.
  • document.getElementById('idofsomefield').getAttribute('value') // this is fetching attribute say "Tom"
  • document.getElementById('idofsomefield').value // this is fetching value property say "Tom"
  • If we try to change the value of "idofsomefield" input text box to "Harry" then it will change "document.getElementById('idofsomefield').value" to "Harry" and it will not change attribute "document.getElementById('idofsomefield').getAttribute('value')" it will remain same as "Tom" which is at time of initialization.


                            
>> ngModule?
app module is root module which bootstrap and launches the module.

e.g. app.module.ts
import { NgModule } from "@angular/core" // ngModule is required to add meta data to an angular module
import { BrowserModule } from "@angular/platform-browser" // is required by all application that run on browser, This module also provides ngIf and ngFor directives.

import {AppComponent} from "./app.component"
import {EmployeeComponent} from "./employee.component"

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent, EmployeeComponent], // component declarations
    bootstrap: [AppComponent] // root component
})

export class AppModule {}


>> How to allow compile on save? what is setting for compile code on save?
Tell TypeScript compiler to compile on save code it need to add/change setting in "tsconfig.json" file by adding '"compileOnSave": true' by using this setting TypeScript compiler will compile file on code save.


>> Css class binding in angular 2?
To bind class to property "[class]" is used.
e.g. replace all the existing CSS classes one or more classes, this type of binding here class "myclass" will get replace with value of "classToApplyVariable"
<button class="myclass" [class]="classToApplyVariable">Click</button>
classToApplyVariable: boolean = true;

e.g. Add or remove single class, this type of binding is used add/delete some classes without removing existing classes
<button class="myclass" [class.boldClass]="applyBoldClass">Click</button>
applyBoldClass: boolean = true;

e.g. To add or remove multiple css classes we can use ngClass directive
<button class="myclass" [ngClass]="addClasses()">Click</button>
addClasses() {
 let classes = {
    boldClass: this.applyBoldClass,
    italicsClass: this.applyItalicsClass
 }
 return classes;
}

>> Css style binding in angular 2?
To bind style to property "[style]" is used.

e.g. append the existing CSS style to given inline style, we can also write "style.font-weight" to "style.fontWeight"
<button style="color: red" [style.font-weight]="isBold ? 'bold': 'normal' ">Click</button>
or
<button style="color: red" [style.fontWeight]="isBold ? 'bold': 'normal' ">Click</button>
isBold: boolean = true;


e.g. Add pixes unit in style, we can specify unit in style like "[style.font-size.px]"
<button class="myclass" [style.font-size.px]="fontSize">Click</button>
fontSize: number = 30;

e.g. To set multiple inline styles using "ngStyle" directive
<button class="myclass" [ngStyle]="addStyles()">Click</button>
addStyles() {
 let styles = {
    'font-size.px': this.fontSize,
    'font-style': this.isItalic ? 'italic' : 'normal',
    'font-weight': this.isBold ? 'bold' : 'normal'
 }
 return styles;
}


>> Event Binding Angular2?
Bellow mentioned bindings flows data in one direction, i.e. from component class property to an html element property,
  • Interpolation
  • Property Binding
  • Attribute Binding
  • Class Binding
  • Style Binding

Event Binding flows data in the opposite direction i.e. from an html element to a component.
For event binding we can use "(click)" or "on-click" like a syntax both will work

e.g.
<button (click)="onClick()">Click me</button>
or
<button on-click="onClick()">Click me</button>
onClick(): void { // if method does not return anything then we can mark return type as void
    console.log('Button clicked');
}

>> *ngIf in angular Js 2?
ngIf - we only use opening of this, the closing tag will get automatically managed with closing of particular element.

e.g.
<td *ngIf="fieldShow">
    Show the contentns
</td> // closing of if is automatically managed here.

e.g.
<tr *ngIf="!employees || employees.length==0">
    <td>No employee records found.</td>
</tr>  

>> Two way data binding in angular 2?
  • Two way data binding is combination of property binding and event binding.
  • The square brackets on the outside are for property binding.
  • The parentheses on the inside are for event binding.
  • To easy remember this syntax, compare it to banana in a box

e.g. [()] 

We can use event binding to flow data in opposite direction. i.e. If we enter data in input text box same value will be reflect to component property.
In bellow example "$event" is contains event data and "name=$event.target.value" here it will assign $event value to component property "name".

e.g.
Name: <input [value]="name" (input)="name=$event.target.value" />
<br/>
You entered: {{name}}
name: string = 'Nilesh';

e.g. we can do two way data binding using ngModel directive
Name: <input [(ngModel)]="name" />
<br/>
You entered: {{name}}
name: string = 'Nilesh';


>> *ngFor in angular Js 2?
ngFor - we need to use "let" keyword in for loop to define the variable.
e.g.
<tr *ngFor="let employee of employees">
   <td>{{employee.name}}</td>
   <td>{{employee.salary}}</td>
</tr> // closing of is automatically managed here.

//in component we can define employees as
employees: any[] [
    {code: 'emp1', name: 'Nilesh', salary: '2'},
    {code: 'emp2', name: 'Manish', salary: '1'},
]


>> How to use TrackBy using ngFor directive?
  • ngFor directive may perform poorly with large lists.
  • A small change to the list may trigger a cascade of DOM manipulations.
  • In ngFor use ;trackBy:functionName to track

e.g.
<tr *ngFor="let employee of employees; trackBy: trackByEmployeeCodeFunction">


>> fetch index of each row/array/collection in for loop?
e.g. to display index we can use "index" in ngFor
<tr *ngFor="let employee of employees; let i= index">
  <td>{{i}}</td>

>> Identify first, last, even, odd element in collection?
e.g. to identify first or last we can use "first", "last", "even", "odd" property in ngFor
<tr *ngFor="let employee of employees; let isFirst= first; let isLast= last; let isEven= even; let isOdd= odd;">
  <td>{{isFirst}}  {{isLast}}  {{isEven}} {{isOdd}}</td>


>> Pipes in angular?
  • Pipes transform data before display.
  • Built in pipes include lowercase, uppercase, decimal, date, percent, currency etc.
  • To apply a pipe on a bound property use the pipe character "|".
  • We can aslo chain pipes.
  • PAss parameters to pipe using colon ":"
  • We can also create custom pipes. 

e.g.
{{employee.name | uppercase}}
{{employee.name | date: 'fullDate'}}
{{employee.name | date: 'dd/MM/y' | uppercase}}
{{employee.name | currency: 'USD': true: '1.3-3'}}


>> create custom pipe in angular js 2?
to create custom pipe use "pipeName.pipe.ts" and use "Pipe, PipeTransform" imports and implement PipeTransform class to custom pipe

e.g.
import {Pipem PipeTransform } from '@angular/core';
@Pipe({
    name: 'employeeTitle'
})
export class EmployeeTitlePipe implements PipeTransform {
    transform(value: string, gender: string): string {
        if(gender.toLowerCase() == 'male') {
            return "Mr. " + value;
        }else {
            return "Miss. " + value;
        }
    }
}
//in view, note to use bellow custom pipe we need to import "pipeName.pipe.ts" file and add "EmployeeTitlePipe" to declarations array
{{employee.name | employeeTitle: employee.gender}}


>> nested components?

  • component which contains component is called nested component or parent component.
  • To make a property an input property decorate it with @input decorator.

e.g.
import {Component, Input } from '@angular/core'
@Component({
....
})
export class EmployeeCountComponent{
    @Input()
    all: number;
  
    @Input()
    male: number;
}


>> filter in compoent?
e.g.
this.employees.filter(e => e.gender ==="Male").length;


>> using two structural directive?
Angular does not allow two structural directives for same html element. can not have multiple template binding on multiple element.
To overcome this issue we can use "ng-container" directive

e.g. // bellow is not supported
<tr *ngFor="let employee of employees;" *ngIf="selectItem">

e.g. ng-container directive
<ng-container *ngFor="let employee of employees;">
<tr *ngIf="selectItem"><td>{{employee.name}}</td></tr>
</ng-container>


>> Interfaces in Angular 2?
  • An interface defines a contract. i.e. shap and structure of api that implementing class must have it.
  • TypeScript is strongly typed language it means every class parameters and method parameter we defined in typescript class has a type associated with it.
  • We can use Interface to create a custom type for objects.  
  • Interface only contains declartions of properties, methods and events.
  • Implementaion of memver of interface is provided by class that implements interface.
  • class that implements interface has to define all the methods/member.
  • It has common convention to have Interface name start with capital letter "I", it is not compulsary to name it like that.
  • Use the interface keyword to create an interface.
  • Interface members are public by default and does not require explicit access modifiers. It is compile time error to include an explicit access modifier.
  • A class that implements an interface must provide implementaion for all the interface members unless the members are marked as optional using the "?" operator.
  • Use implements keyword to make a class implement an interface.


Interface in TypeScript -

  • TypeScript interfaces exist for developer convenience and are not used by Angular at run time. During the transpilation, no JavaScript code is generated for an interface. It is only used by TypeScript for type checking during development.
  • To reduce an amount of code you have to write consider using short hand syntax to initialize class properties with constructor parameters.


e.g. employee.ts
export interface IEmployee {
    code: string;
    name: string;
    gender: string;
}
//we can use above interface as empoyee type for array declaration in component file
e.g. employee.component.ts
import {IEmployee} from './employee';

// we can delcare employees type as "IEmployee"
employees: IEmployee[];


>> Angular component lifecycle Hooks?
  • A component has a lifecycle managed by Angular. Angular
  • Creates the component
  • Renders the component
  • Creates and renders the component children
  • Checks when the component data bound properties change, and
  • Destrooys the component before removing it from the DOM.
  • To include hooks we need to implement interfaces. like OnChanges with SimpleChanges hook interface from '@angular/core'


To tap into and react when these life cycle events occur, angular offers several lifecycle hooks methods,
ngOnChanges --
commonly used, this is called before ngOnInit, This executes every time the value of an input property changes. The hook method recives a SimpleChanges object containing "current" and "previous" property values.
ngOnInit -- 
commonly used, Executes after the constructor and after ngOnChange hook for the first time. It is most commonly used for component initialization and retriving data from a database.
ngDoCheck
--ngAfterContentInit
--ngAfterContentChecked
--ngAfterViewInit
--ngAfterViewChecked
ngOnDestroy  --
commonly used, Executes just before angular destroys the component and generally used for performing cleanup.
e.g. 3 steps to use the life cycle hooks
step 1: Import the Life Cycle Hook Interface
import { OnInit } from '@angular/core';
step 2: Make the component class implement the Life Cycle Hook Interface
export class SimpleComponent implements OnInit
step 3: write the implementation code for the life cycle interface method
ngOnInit() {
    console.log('Onint life cycle hook');
}


>> Angular services?
  • A service in angular is generally used when you need to reuse data or logic across multiple components. without the service you would have to repeat a code.
  • ngOnInit life cycle hook is the best place to call the service. We can also call service in contructor but if network (http to remove server) takes time to load the data page then service also get delayed.
  • ngOnInit loads after the constructor and its most commonly used for initialization of components and making service calls.
  • It need to use "providers" property of component annotation call in which component we are using the service.
  • we can register a service to Injector with component level or module level using "providers" property. Angular Injector injects the dependency to component.


e.g. to create service we need import Injectable class from core, employee.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class EmployeeService {
    getEmployees() : IEmployee[] {
        return [{employe1Data}, {employe2Data}, {employe3Data}];
    }
}

//in component we call import and use service
import { Component, OnInit } from '@angular/core';
import { IEmployee } from './employee';
import { EmployeeService } from './employee.service';
import {}

@Component({
selector: 'list-employee',
templateUrl: 'employeeList.component.html',
providers: [EmployeeService]
})
export class EmployeeListComponent {
conmstructor( private _employeeService: EmployeeService) {}
ngOnInit() {
    this.employees = this._employeeService.getEmployees();
}

}


>> HttpModule for calling external service in angular js 2?
  • HttpModule this is built in angular service to call the webservice angular.
  • To call the http serivce in angular httpmodule is used. we need to use the import {HttpModule} from angular/http.
  • We need to use Http service from HttpModule in angular custom service that we created.


e.g.
import { HttpModule } from '@angular/http'
@NgModule({
    imports: [HttpModule]
})

//in our custom service we need to import Http service
import { Http } from '@angular/http'

//initialize service class constructor
constructor(private _http: Http) {}

//create/call GET call using http service
this._http.get('http://example.com/api/employees');

e.g. employee.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/throw';

@Injectable()
export class EmployeeService {
    constructor(private _http: Http) {}
  
    getEmployees() : Observable<IEmployee[]> {
        return this._http.get('http://example.com/api/employees/')  // get call to api
                            .map((response: Response) => <IEmployee[]> response.json()) // to map/callback to format data
                            .catch(this.hadleError); // for error handling need to implement/call "hadleError" function error logic
    }
    hadleError(error: Response) {
        console.error(error);
        return Observable.throw(error); // throw error to calling service component to handle error
    }
}

//to subscribe to observable we need to use subscribe method with callback function in component that using service
ngOnInit() {
    this.employees = this._employeeService.getEmployees().subscribe((employeeData) => this.employees = employeeData,
                                                                    (error) => { this.statusMessage = 'problem with service, please try later'});
}


>> Observable pattern?
  • An Observable is asynchronous pattern.
  • In this pattern we have observable and observer, observable emmits data items on notification and observer it is also called as subscribe can subscribe to the observable. when subscribing to observers sepcifies a call back function and that callback function of the observer also called as subscriber is notified when ever the observable emmits data items in that code we write code to handle the data items. 
  • An observable can have multiple observers anybody who is interested in data from a observable can observe the observable meaning that can subscribe to observable in observer when subscribe lets specify callback function in that funtion we have code to handle the data emited by observable.

e.g.
                          | -> observer/subscriber
Observable   -> | -> observer/subscriber
                          | -> observer/subscriber



>> Routing in angular js?
Routing allows us to navigate from one view to another view. i.e. routing is used to navigate between components.
e.g.
set the <base href="/"> in index.html

//add nav menu and refer route
<a routerLinkActive="active" routerLink="home">Home</a>
<a routerLinkActive="active" routerLink="employees">Employees</a>

//render routed component to this location
<router-outlet></router-outlet>

//then write route to main entery component file
import { RouteModule, Routes } from '@angular/router';

const appRoutes: Routes [
    {path: 'home', component: HomeComponent},
    {path: 'employees', component: EmployeeListComponent},
    {path: '', redirectTo: '/home', pathMatch: 'full'},
    {path: '**', component: PageNotFoundComponent}          
];

@NgModule({
    imports: [
        RouteModule.forRoot(appRoutes)
    ],
});


>> Binding route parameter?
e.g.
    {path: 'employees/:code', component: EmployeeListComponent}
<a [routerLink]="['/employees', employee.code]">{{employee.code | upperCase}}</a>  


>> What is dependency injection?
  • It's a coding pattern in which a class recieves its dependency from an external source rather than creating them itself.
  • With Dependency Injection it is very easy to mock objects when unit testing.
  • If we use Dependency Injection (DI), the angular injector provides a Singleton instance so that for every component only one instance can be share.
  • With dependency we have external source (i.e. Angular Injector) is creating the dependency instance, the Computer class need not change when the processor class changes.



Benefits of Dependency Injection -
  • Create applications that are easy to write and maintain over time as the application evolves.
  • Easy to share data and functionality as the angular injector provides a Singleton .i.e. single instance of the service.
  • Easy to write and maintain unit tests as the dependecies can be mocked.


e.g. we need to build a computer in order to build computer we need several components like ram, harddisk, processor,
computer class has dependency on processor class, So to build computer we need object of processor class/
export class Computer {
    private processor: Processor;
    constructor() {
        this.processor = new Processor();
        //using above approach using create instance using new keyword has some disadvantages
        This code is difficult to maintain overtime. (if processor class changes constructor parameter then computer has to also change initialization of processor with parameter)
        Instances of dependecies created by a class that needs those dependencies are local to class and can not share data and logic.
        Hard to unit test.
    }
}
export class Processor {
    constructor() {
    }
}


>> Angular Injector?
Angular Injector -
  • First we need to register service in injector.
  • With in the comoponent specify dependency of service using constructor parameter.
  • So whenever instance of component is created the Injector will automatically going to inject an instance in to this component.
  • In angular 1 we have only one global injector, But in angular 2 we have hirachical tree of injector.
  • If we register service at root level of app injector then that service will available for injection to all components including lazy loaded module components.


e.g. we have one root injector plus one injector at every level of component.
Root App Injector
App Component - injector
Compo x - injector  Comp A - injector
Compo y -injector
Compo z - injector


>> Angular router navigate method?
navigate() method is used to navigate between one pahe to another page.
We need to import 'Router' service for this.
e.g.
import { ActivatedRoute, Router} from '@angular/router'

//initialize router service in component
constructor(private _router: Router) {}

//to navigate we can use on button click etc.
onBackButtonClick() {
this._router.navigate(['/employees']); // pass path of router to navigate to
}

>> Using promises intead of observable in angular 2?
  • In angular we can use promises or observable, in angular built in http service by default it returns as observable. 
  • we need to use "toPromise()" method to transform Observable to Promise.
  • In component instead of using "subscribe()" method we need to use "then()" method and need to implement catch method to catch errors.

e.g.
import 'rxjs/add/operator/toPromise';

    getEmployeeByCode(empCode: string) : Promise<IEmployee> {
        return this._http.get('http://example.com/api/employees/' + empCode)  // get call to api
                            .map((response: Response) => <IEmployee> response.json()) // to map/callback to format data
                            .toPromise()
                            .catch(this.hadleError); // for error handling need to implement/call "hadleError" function error logic
    }



>> Difference between Promises and Observble?
  • Promise emits a single value, wher Observable emits multiple values over a period of a time. In promise we have only one callback function .i.e. "onfulfilled", where as in Observable there are two callback functions "next" and "complete". 
  • If observable emits callback function with multiple values then same funtion "next" will be called multiple times and for last item the "complete" method gets called.
  • A promise is not Lazy (service call alway issue wheather then method is implemented or not), whear as Observable is lazy. An Observable will not called until we subscribe to the Observable using subscribe method.
  • Promise can not be cancelled, Observable has "unsubscribe()" method using this it can be cancellable.
  • Observable provides many powerful operators like map, forEach, filter, reduce, retry, retryWhen etc.



>> How to re-subscribe and retry an observable?
We can use retry operator/method to re subscribe to observation for specific attempts.
We can also use retryWhen operaor/method using this we can output specific error and delay the execution for specified time and retry. We can also scan function instead of delay function,
e.g.
import 'rxjs/add/operator/retry';

this.employees = this._employeeService.getEmployees()
                    .retry(3) // if we not provide any number then it will run request infinite times till service return any output
                    .retryWhen((err) => err.delay(1000)) // delay exection for 1sec, this retries request on every 1 sec.
                    .retryWhen(
                    (err) => {
                        return err.scan((retryCount) => {
                            retryCount +=1;
                        }, 0).delay(1000)
                    })
                    .subscribe((employeeData) => this.employees = employeeData,
                     (error) => { this.statusMessage = 'problem with service, please try later'});


>> Angular Observable Unsubscribe?
e.g.
import { ISubscribe } 'rxjs/Subscription';

subscription: ISubscribe;

onCancelButtonClick() {
    this.subscription.unsubscribe();
}

//to check suscription to service is cancelled/closed we have 'closed' propery.
this.subscription.closed;


>> Angular CLI

//Editor
visual studio code editor for ubuntu and other OS

//Angular 5 cli inbuilt authentication
ngx-rocket -> generator-ngx-rocket

//Angular 4 video tutorial
https://www.youtube.com/channel/UCs9aSFGylGbHPrEg4dzy3sQ/videos

$ npm install -g @angular/cli
$ ng -v // to know latest version of angualr cli, ng it self is angular cli
$ ng new projectName // angular project create using angular cli
$ ng serve -o // launch application in default browser
$ ng g c componentName --spec false --flat true // g- generate, c- component, this will create component.ts, .css and .html file and it will also update app.module.ts
$ ng serve -o --base-href /emp/  // this will set base path from "/" to "/emp/" so applicatio will run like,  http://localhost:4200/emp/list
$ ng build -prod --base-href /emp/  // if production server on "/emp/" subfolder then run/start server using this

OR

we can use bellow to generate angular app using login authentication inbuit -
https://github.com/ngx-rocket/generator-ngx-rocket



>> Angular from scratch?
Angular from scratch need to have bellow steps,
Create application folder and add configuration files.
Install the packages // package.json
Create root application component. // src/app/app.component.ts, every angular application should have atleast one component, And this root component bootstraps the angular component.
Create root application module. // src/app/app.module.ts
Create main.ts file // entry point of application loads application module and module loads application component
Create index.html // on root on main.ts level create index.html


>> Angular 4 folder structure?
e2e/
node_modules/
src/
--favicon.ico
--index.html  //  is the landing/main page of our application and this is where our angular app bootstraps.
--main.ts  // is the main typescript file which is used to bootstrap the angular module, check for environment is also performed here.
--polyfills.ts
--styles.css
--test.ts
--tsconfig.app.json
--tsconfig.spec.json
--typings.d.ts
--app/  //app directory is where we define the building blocks of our angular project like modules , components , services
----app.module.ts  // In this file , we declare our angular module, @NgModule decorator is used to initialize different aspects.
----app.components.ts  //  this file simply defines an angular componen
----app.component.html  // this is the template file for our app component and this represents the visual part.
--assets/  //this directory contains all the static assets of our app like images etc.
--enviornment/  //different configuration files for development , testing and staging etc.
.angular-cli.json // .angular-cli serves as a blueprint to the @angular/cli tool.
karma.config.js
.editorconfig
.gitignore
package.json
protractor.json
tsconfig.json // if there's a tsconfig file in a directory , that means that directory is a root directory of a typescript project , moreover it is also used to define different typescript compilation related options.
tslint.json



>> Some questions and Points/Summary which we should know about Angular 2
>> TS config documentation?
>> type script compiler
>> lite server
>> Reactive extensions
>> Observables
>> calling back-end services.
>> Difference between declaring variable using Var and Let?
>> *ngIf
>> *ngFor
>> ngClass
>> ngStyle
>> ngModule  -> @angular/core
>> RouterModule -> @angular/router -> Routes -> for ruoting purpose
>> ActivateRoute -> @angular/router -> service provided by angular, If we provide service/service instance in constructor then angular will provide us automatically us. e.g. this._activatedRoute.snapshot.params['code']; // code nam of param in route "/empoyee/:code"
>> HttpModule  -> use to call service/api
>> BrowserModule -> @angular/platform-browser -> BrowserModule -> ngIf, ngFor
>> FormsModule -> @angular/forms -> FormsModule -> ngModel
>> ngModel -> to achieve two way data binding
>> ng-container -> to avoid multiple structural directive issue
>> Component
>> Input
>> Output
>> EventEmiter
>> Angular cli
>> @angular/common
>> @angular/compiler
>> @angular/core
>> @angular/forms
>> @angular/http
>> @angular/platform-browser
>> @angular/platform-browser-dynamic
>> @angular/router
>> angular-in-memory-web-api
>> core-js
>> rxjs
>> systemjs
>> zone.js
>> Observable
>> Promises
>> What is component?
>> Creating a component and a nested component.
>> Passing data between parent and child components.
>> Different ways of applying styles to components.
>> Interpolation, property binding, class, style and event bindings.
>> Two way data binding
>> Structural directives *ngIf and *ngFor
>> Built in angular pipes and creating our own custom pipes.
>> Creating custom types using TypeScript interfaces.
>> Component lifycycle hooks
>> Creating service that retrives data from a remote web service.
>> using bootstrap to sytle angular components.
>> how routing works in angualr and passing parameter to routes.
>> What is dependency injection and how it is implemented in Angular.
>> How to work with Observables and Promises in angular

reference links : -
https://www.youtube.com/watch?v=_-CD_5YhJTA
https://www.youtube.com/watch?v=WWQZCDegWHg&list=PL6n9fhu94yhWqGD8BuKuX-VTKqlNBj-m6
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Comments

Popular posts from this blog

Learn phpfox

PHPFox  is a social network script, it is an internet application and when you install it, it is a website. The  phpfox  script comes in 3 packages, each with a different set of modules. it has two products: 1. Nebula (upto phpfox 3.8) 2. Neutron (Newer) You can check the demo on :  http://www.phpfox.com =================================================== To clear cache in phpfox follow the following steps, admincp >> Tools >> Maintenance >> Cache Manager >> Click on Clear All button =================================================== To work facebook app on local Following settings need to done in facebook app   1) go => setting => Advance 2) see "OAuth Settings" area and set "Valid OAuth redirect URIs" =  http:// projectdomain /index.php?do=/user/login/, http:// projectdomain .com/index.php?do=/user/register/, http:// projectdomain .com, http:// projectdomain .com/index.php 3) en...

Interview PHP

>> Why do you want to work at our company? Sir, It is a great privilege for anyone to work in a reputed company like yours. When I read about your company I found that my skills are matching your requirements.  Where I can showcase my technical skills to contribute to the company growth. >> What are your strengths? I am very much hard working and optimistic. Hard Working: Work with dedication and determination. Optimistic: work with positive attitude. I am a team player. I am also very hardworking, and will do what it takes to get the job done. >> What are your weaknesses? Gets nervous when talk to strangers I am a bit lazy about which I am not interested I tend to trust people too easily. I am working on it. >> Why should I hire you? With reference to my work experience, I satisfy all the requirement for this job. I am sincere with my work and would never let you down in anyway. I promise you will never regret for the decision to a...

How to Make Your Own PHP Captcha Generator

In this article we will create file based simple yet successful captcha generator. 3 Major Anti-spamming techniques used? Mathematical Operation like Random number + Random Number = -> The user must specify the answer Random word -> User must type the word Random question -> Obvious one which the user should answer correctly [ex: Are you human?] How Captcha works? The captcha generator generates an IMAGE with the question and then put up a session variable storing the value. User input though an input box. Using php POST, we compare the session variable data with the user input and tell whether its a bot or human. Its coding time The Code First let's write the php script which generates the captcha image. We use the simple header-content change technique, from which we can easily bring up an image from a given text. captcha.php PHP Code: array("Num" => "Num"), 1 => array("Are y...