Angular 2 Property Binding

 

Hello everybody,

today I want to write few words about binding in AngularJS 2.

There are two ways of making one way binding:

  1. element property binded to template expression
  2. property interpolation

I've described it with following picture:

Two-way Binding

<input [(ngModel)]='property'>

And property is decalred in Component class like this:

export class ClassComponent {

       property: string = "Property value";

}

No Comments

Add a Comment
 

 

Typescript Class Creation

 

Hello everybody,

today I want to document some demos for class declaration in Angular 2. 

So, let's say you have following class declared:

Snippet

import { Component, Injectable } from '@angular/core'
import { Http, Response } from '@angular/http'
 
@Component({
})
 
export class Config {
    public apiKey: string = 'xxxxxyy117c24d8b9085187163f5d241';
    public url: string = 'https://public-api.blablacar.com/api/v2/trips?key=';
 
    constructor(private http: Http) {
    }
 
    getReqUrl(): string{
        return this.url + this.apiKey;
    }
}

Then the way to create it is the following:

Snippet

findTrips()
{
    let conf = new Config();
    let url: string = conf.getReqUrl();
 
}

Take note, tht for conf we didn't put type clarification, but for url we clarified the type of variable.

No Comments

Add a Comment
 

 

Observables In Angularjs 2

 

Hello everybody,

today I want to write a few words about totally new feature in AngularJS 2 which is entitled Observables. Observables to some degree feet to promises, but still have some differences. They are mentioned in following table:

Promise Observable
Single feature value Emits multiple values over time
Not lazy Lazy
Not cancelable Cancelable
  supports map, filter, reduc and similar operators

No Comments

Add a Comment
 

 

Building A Custom Pipe In Angularjs 2

 

Hello everybody,

today I want to write few words about custom pipes in ... AngularJS 2. The first time when I've heard about custom pipes happened to be when I've learned powershell scripting. And recently I've discovered that there are some built in custom pipes in AngularJS 2 and we can make our own custom pipes. 

What is needed for implementing custom pipes? Nothing special. Just import from AngularJS 2 PipeTransform and implement in it method transform. And one more is pipe decorator ( in my example something that starts from @Pipe and ends with first }) ). And what else? Of course import statements.

It can look like this:

import {Pipe, PipeTransform} from '@angular/core'

@Pipe({name: 'studentsFilter'})

export class StudentFilterPipe

             implements PipeTransform {

                transform(value: IStudent[], filterBy: string) : IStudent[]{

                }

}

And that almost it. You have custome pipe for Students. 

Then in html code it will look like this:

<tr *ngFor='let student of students | studentsFilter : studFilter'

No Comments

Add a Comment
 

 

What Is Service In Angularjs 2

 

Hello everybody,

today I want to write few words about AngularJS 2 services, or if to be more specific what is Service in angular at all? If to speak very very shortly: Service - it's a class with focused purpose independent from any particular component. It can be caching purpose, or logging purpose, or sending http requests purpose. 

Lets say you need to build a service in AngularJS 2. You'll need to go through the following steps:

  1. Create class for service
  2. Define metadata with decorator
  3. Import what is needed for service

import { Injectable } from '@angular/core'

@Injectable() //needed if we have injected dependency or for consistency

export class StudentsService{

        getStudents() : IStudent[]{

        }

}

One more important detail about Services. As usually services have lifetime as singletons. Why I say as usually? Because you can have two or even more instances of service, if you register them in parallel components. Then Angular will crate two instances of your service. It's not nesessary bad. It's just something that you maybe not expect to receive. 

No Comments

Add a Comment
 

 

Angular 2 Data Binding And Pipes

 

Hello everybody,

today  I want to make short note about types of Data Binding in AngularJS 2.

here they are:

  • Interpolation. It looks like this in code: {{firstName}}
  • Property binding. Sample in code: <img [src]='person.photo'>
  • Event binding. Html code pattern: <button (click)='showMessage()'... />
  • Two-way binding: <input [(ngModel)]='someProperty' />

Important think to remember about usage of ngModel is the following:

in your imports add importing of FormsModule.

For example like this:

@NgModule({

       imports: [

          BrowserModule,

          FormsModule]

       declarations: [

          AppComponent,

.......

       ]

   })

export class AppModule {

}

If you need formatting you can use pipes. Example of currency pipe:

{{ product.price | currency: 'USD' : true: '1.2-2' }}

This piping means the following: display as currency with $ sign, use at least 1 number for initial position, with at least two positions after comma and at most two positions after comma.

No Comments

Add a Comment
 

 

What Is Angularjs 2 Component

 

Introduction

Here I want to write of how I grasped what is Angular 2 component building blocks

Hello everybody,

I don't know about you, but when I first opened AngularJS 2 component source code, I've become puzzled with question mark of what is AngularJS 2 component?

Imagine, that you look at this sampe:

import { Component } from '@angular/core';

@Component({
       selector: 'my-app',
       template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'Angular'; } 

and try to figure out what are consisting parts of compoment? After watching on that example and some others example here is conclusion that I've made:

Do you remember previous fragment of code? Take a look with explanation of those hexagons:

hope this hexagons along with green rectangles will make your understanding of what makes AngularJS 2 component easier.

Now let's go deeper in this fragment of text:

export class AppComponent { name = 'Angular'; } 

Or even we will fromat it a bit better to make understanding deeper:

export class AppComponent {

         name: string = 'Angular';

} 

Next goes understanding of what is metadata or this part of code:

@Component({
       selector: 'my-app',
       template: `<h1>Hello {{name}}</h1>`
})

Before continuing with another drawings, following  understanding will be needed: Decorator. In other words, decorator is function that adds metadata to something. That something can be class, members, method arguments. Few other features of decorators:

  • prefixed with @
  • Angular provides built-in decorator which is named @Component
  • decorater is applied to something, before it is described
  • if you are from C# world ( as I am ) you can compare decorator with attributes

Take look at it on the screen with rectangles as well:

Few other words related to that description.

selector property says to AngularJS 2: please define for me selector 'my-app'

component also defines template. The one which is described. 

And {{name}} indicates data binding. It means that field name will get value name from the class AppComponent.

I hope this explanations will help to make understanding of AngularJS 2 components little bit more structured for somebody

No Comments

Add a Comment
 

 

How To Call Method Of Angularjs Controller Outside Of Angularjs In Javascript

 

Hello everybody,

today I want to write few words about AngularJS and js integration.

Recently I had opportunity to cowork with one guy, which is great in knowing javascript, but absolutely hates to learn and apply AngularJS. So, I had task in front of me, to give him sone kind of JS object, which he can use in order to execute some method of AngularJS controller.

So I had some AngularJS controller. 

here is the fragment of it:

'use strict';
 
var controller = 'toolBoxController';
 
angular
    .module('examples')
    .controller(controller, TbController);//register

Then I've added class ( in terms of javascript ):

(function (window, undefined) {
    function toolBoxObject() {
//this function finds controller, which is binded to toolBox div, and executes method of it
        this.unSelect = function () {
            var scope = angular.element('#toolBox').scope();
            scope.$apply(
                    function() {
                        angular.element('#toolBox').controller().unSelect();
                    }
                );
        }

And then in controller I had following method:

var tbObject = new ToolBoxObject();
 
function TbController() {
    var vm = this;
    vm.tb = tbObject;
    vm.ToolBoxButtons = new Array();
    tbObject.controller = this;
//etc.....

And then following method was intended for execution:

vm.unSelect = function () {
 //some kind of implementation
}

I'm ready to bet that you want to ask, why on earth it was needed to use 

var scope = angular.element('#toolBox').scope();

and not just execute mehtod of controller. Well, the answer is simple without scope, the method of controller was executed but results of execution wasn't displayable at screen, and with apply results was possible to show on the screen.

No Comments

Add a Comment
 

 

Angularjs Clean Code Advices

 

Hello everybody,

today I want to share with you fragment of knowledge from John Papa and his course at pluralsight entitled AngularJS Patterns: Clean Code.

Inside of course one of the videos he have following structure advice: Function, Inject, Register ( I will name it FIR  ).

function DashBoardController(service1, service2) {//function

    //here goes code of controller.

}

DashBoardController.$inject = ['service1', 'service2'];//inject

angular

    .module('app')

    .controller('DashBoardController', DashBoardController);//register

or in the form of image:

And as John Papa mentioned, Todd Motto also likes that approach:

"I prefer this sequence: write my function, inject the dependencies, ship it off into the app. It makes sense from hoisting and declarative prospectives".

 

But in one of projects where I used to work, company had another approach: Register, Inject, Function. You maybe can ask: "Why?". The answer is pretty simple: if your function is pretty big, then it can be not convenient to scroll it

No Comments

 

Add a Comment
 

 

Angularjs Inheritance In Js

 

Hello everybody,

today  I want to write short notice about another useful feature of AngularJS particularly about extend function.

So, according to comment in angular.js file function extend does the following:

/**
 * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
 * to `dst`. You can specify multiple `src` objects.
 *
 * @param {Object} dst Destination object.
 * @param {...Object} src Source object(s).
 * @returns {Object} Reference to `dst`.
 */
function extend(dst) {
  //herer goes implementation
  return dst;
}

You may wonder, why do I need this? 

Well, one of the reasons, is imitiating inheritance in some way, additional modularty, but without usage of prototype. Is it useful? I believe at least for somebody it will be.

No Comments

 

Add a Comment