Autor: Marcos Cereijo Rodríguez

Web Technologies – Angular (Part 2)

by Marcos.Cereijo | In a previous post we took a brief overview about Angular and its evolution. Now it’s time to go a bit deeper.

We are going to talk about how a component is able to display the value of its properties in the template and, the other way around, how a template can inform about events and input values to the component. We are also going to see how to modify the DOM structure based on the component state. Finally, we are going to get a glimpse about how to import and use SippoJS in an Angular application.

For explaining these topics we will assume that we have developed a component called Hero. For using this component, we only have to add the hero tag to an HTML template. For example:

<div>Below I will get a instance of the HeroComponent</div>
<hero></hero>

The following excerpt represents the file hero.component.ts in which we defined the HeroComponent:

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

@Component({
  selector: 'hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})
export class HeroComponent {
  myHero: string = 'Superman';
  myHeroImage: string = 'img/superman.png';
  Heroes: string[] = ['Superman', 'Batman', 'Wonder Woman', 'Hulk'];
  myClickHero() {
      console.log('My hero is ' + this.myHero);
  }
}

One important thing about the previous code is that we pass a lot of interesting metadata to the component through the @Component() decorator:

  • selector: Defines the tag name that we will use to get an instance of this component.
  • templateUrl: Represents the path to the HTML template that this component will use.
  • styleUrls: It’s an array with stylesheets that we will use for this component.

Now we are going to see how to write a hero.component.html file which will be able to communicate with the component.

Data Binding

Through data binding we can get variables values from our component and display these values in the template. We also can do it the other way around. Get information and events from the template to the component.

  • Interpolation: This allow us to display component properties inside our templates. In this case, the <p> node will have inside the value of the variable between the double curly braces.
    <p> {{ myHero }} </p>
    
  • Property binding: We can attach a variable value to a HTML DOM property. In this case we do so to the image src property. We need to know that we aren’t talking about HTML attributes. Some properties have the same name that an attribute, but the are cases that they haven’t an attribute equivalent or their behavior can differ. This is the case of the disabled attribute and property. The only presence of the disabled attribute will produce a property disabled=true. The value of this attribute doesn’t matter for the browser. In the following example we will assign the myHeroImage value to the src property.
    <img [src]='myHeroImage'>
    
  • Event binding: This allow us to run code in the component just by triggering an event. For example through a click on a button. We also can define our own events using the directive EventEmitter.
    <button (click)='myClickHero()'>Click Here!!!</button>
    
  • Two way data binding: This binding type is the most useful, due to it works in both directions. If we modify the value in the template, it will be modified in the component and if we modify the value in the component, it will be changed in the template.
    <input [(ngModel)]='myHero'>
    

Structural Directives

These are directives which modify the DOM structures. This allow us to add or remove HTML elements dynamically.

  • Directive *ngFor: If we need to create several nodes of the same type, we can use this directive. In this example we create a <li> node for each element inside the heroes array.
    <ul>
        <li *ngFor='let hero in heroes'>{{ hero }}</li>
    </ul>
    
  • Directive *ngIf: This directive enables or disables a section just depending on a condition. This is very efficient because we aren’t hiding or displaying the element. This help us to save memory, because we are adding and removing them from the DOM on demand.
    <div *ngIf='heroes.lenght > 3'>Too many Heroes</div>
    

Angular has some more structural directives such as *ngSwitchCase and *ngSwitchDefault that work in a similar way that these two.

 

SippoJS and Angular

For using SippoJS we just have to add the package name and version to our package.json and import it in our source files. Once we have done this, we will be able to use SippoJS in the same way that before, but taking advantage of all the TypeScript features.

In the following example we can see and excerpt of an Angular authentication service using SippoJS:

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

import * as Sippo from "@quobis/sippojs";

@Injectable()
export class AuthService {

  authenticated: boolean = false;

  login(username: string, password: string): Promise {

    let sessionConfig = {
      wacUri: this.config.wacUri,
      mediatypes: {
        audio: true,
        video: true
      }
    }

    return Sippo.createSession(username, password, sessionConfig). then(
      session => {
        this.session = session;
        return session.connect().then( () => {
          this.authenticated = true;
          return session;
        });
      }
    );
  }

  . . .

}

 

Conclusion

Angular can help us to build high modular applications and to separate the logic from the template and style. We didn’t talk about it, but in our projects we should use the testing capabilities that will help us to guarantee that changes in our code won’t affect features that were working before.

Starting to use Angular isn’t easy, but once we start, we will notice that the quality of our code and our coding speed, improve. I hope that this Angular introduction could help you to understand what Angular is and how you can take advantage of all these features to build your high quality Sippo application.

This is all for now, but in the next posts we will talk about some technologies that can help us to style our applications and build them for production.

References

[1] Angular: https://angular.io/docs

Web Technologies – Angular (Part 1)

by Marcos Cereijo

This is the first post of a serie about web technologies that we can use to build high quality SippoJS applications. These topics can be very dense so we will only offer an overview of these technologies.

In the following weeks we will introduce some other tools, such as the framework for styling our web page or the tool for generating the packages for production.

Introduction

Building a pure JavaScript application without the help of any framework is an arduous task and error-prone. Therefore, the best idea is to choose one of the available frameworks to start building our application.

We have a lot of JavaScript frameworks to choose. Some of the available frameworks are ReatJS, Vue.js, Meteor.js and Ember.js. However, our selection is the one with the largest community, Angular.

Angular is powered by Google and it was previously introduced as AngularJS.

AngularJS (1.x)

AngularJS is a JavaScript framework that  was launched in 2010. When it arrived, it was one of the biggest surprises of the year. It offered to the developer a fast way to create MVC applications and write tests. It simplified a lot of task that can be a headache like model-view communication, http data retrieval or writing unity and end-to-end tests .

Nowadays a lot of developers continue to use this version of the framework although a newer version was released.

Angular (2.x)This version of Angular was released on 2016 and it was released in two flavors: JavaScript and TypeScript. However the TypeScript version is strongly recommended. The inclusion of TypeScript is the reason of the name changing from AngularJS to just Angular.

Nevertheless the main disadvantage about this version is that it is incompatible with AngularJS. This is the reason why a lot of developers are still using AngularJS and they don’t step forward using Angular.

One thing that we need to know is that the browsers doesn’t understand TypeScript. The code should be transpiled to JavaScript in order to be understood by the browsers.

However this disadvantage is clearly overcome by the new features that TypeScript offers us:

  • Static typing: JavaScript doesn’t have variable types. With JavaScript you can assign an integer to a variable and later a string. This way we don’t need to know anything about variable types, but this is error-prone and potentially dangerous. TypeScript come to solve this issue.
  • Classes: With JavaScript you can simulate this behaviour, but it is difficult to understand and it generates low quality code. TypeScript gives us classes in a similar way that Java does.

TypeScript:

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

JavaScript:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();
  • Code linting: The text editor will give us feedback about the errors in our code at the same time we are programming.
  • Inheritance: This will allow us to reuse and extend our classes with new attributes and methods.

To be able to use SippoJS or other JavaScript libraries inside a TypeScript application, we have two alternatives:

1 – Rewrite the entire library to TypeScript.

2 – Create a definition file to reuse the JavaScript library.

The first solution isn’t a good idea. You need almost to start from scratch and you should maintain booth libraries. The second solution, however, allow us to reuse the code we have developed and to add all the TypeScript capabilities. Clearly we have chosen the second alternative.

Another difference with AngularJS is that they stopped using controllers and scopes. Now everything is a component.

Components are TypeScript classes that are used to display data in the templates. which is their only purpose. They don’t retrieve data from a backend and neither do complex tasks. If we need to do so, we will need to use the Services.

Angular (4.x.x)

This is the current angular version. It doesn’t include many changes and it is just an evolution. This is the version that we have chosen for our new projects.

The angular team decided to use the version number 4, instead of 3. The reason to do so is that they were forze to launch a new version of their routing package. With this change all the package versions are now aligned. That means that if you use @angular/core: 4.0.0, it will be compatible with @angular/router: 4.0.0.

They also started using semantic versioning. That means that the version number will have three numbers separated by dots (major.minor.path). The meaning of this numbers are:

  • Major: Potential breaking changes.
  • Minor: New features, but without breaking changes. All should be working as before.
  • Patch: Bug fixing.

Now the goal of the Angular team is to forget the version number and call their product just Angular. Their plan is to launch a major version each 6 months and periodic patches.

Conclusion

In this post we got an overview about what Angular is and its history. In the next post about Angular we will get a glimpse about Angular template binding and how to import the SippoJS library in TypeScript.

References

[1] AngularJS: https://docs.angularjs.org/guide
[2] Angular: https://angular.io/docs