Web Programming TutorialsLearn about the prevailing three core concepts of Angular 2

Learn about the prevailing three core concepts of Angular 2

Core Concepts
In this article, we are going to discuss about the prevailing three core concepts of Angular 2.
They are:

  • Components
  • Dependency injection, and
  • Bindings.

concepts
Components
In Angular 1, we were using directives, controllers, and scopes to build an application. Now, in Angular 2, all those concepts are combined into Components. The Components are important building blocks. Each component has the following properties.

  • A component is self-describing: We define a template either writing the HTML or through templateUrl that points to a HTML file. The templates are defined within the @Component annotation. It describes how the component is going to be rendered on the web page.
  • A component has precise inputs and outputs: In component, we can define the inputs as well as output through annotations @Input and @Output respectively.
  • The lifecycle of a component is well defined: In Angular2, the component has Input and Output. When there is a change in the input properties, the component will be notified and hence the output will also vary.

The following is an example of an Angular 2 component that provides the employee details.

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Employee } from './employee';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'my-employee-detail',
  templateUrl: 'resource/employee-detail.component.html',
  styleUrls: ['assets/employee-detail.component.css']
})
export class EmployeeDetailComponent implements OnInit {

  @Input() employee: Employee;
  
  constructor(
  	private employeeService: EmployeeService,
  	private route: ActivatedRoute) {
  	
	}
  ngOnInit(): void {
  	this.route.params.forEach((params: Params) => {
    	let id = +params['id'];
    	this.employeeService.getEmployee(id)
      	.then(employee => this.employee = employee);
  		});
	}
  goBack(): void {
  	window.history.back();
  }
}

Explanation of employee-detail.component.ts (typescript file)

  • In the above typescript file, we have defined a component which has the selector as ‘my-employee-detail’, template URL as ‘assets/employee-detail.component.html’ (which has the actual HTML code) and style Urls as ‘assets/employee-detail.component.css’ (which has the styles for the template to render it on the browser). Therefore, the component here is self-describing.
  • The component has the controlling class (here ‘EmployeeDetailComponent’) which controls the input. Here, we have defined a constructor that defines the private properties as ‘EmployeeService’ and ‘ActivatedRoute’. The constructor is used only for the simple initializations such as the wiring of the constructor parameters to properties, etc. and it should not be used for heavy lifting. Therefore, in Angular 2 we do heavy lifting using the implementation the Angular 2 ngOnInit Lifecycle Hook. Angular 2 offers a number of interfaces which can be used to tap the critical moments that occurs in the component lifecycle (i.e. at the time of creation, after each change, and its eventual destruction as it goes out of scope). Each such interface has a single method (e.g. ‘ngOnInit ()’ method present in OnInit interface, etc.). When such a method is implemented by the component, then the Angular 2 calls it at the appropriate time for which it is intended for.
  • The controlling class is also defined with a method ‘goBack ()’ which has a return type as void and is used to navigate a page back from the browser history.

Dependency Injection
What could be the idea behind dependency injection? Here is the answer. We have a component and a service. Now a component depends on this service, in such a case we do not to create the service ourselves. Instead, we may request such a service in the constructor which can be provided by the Angular 2 framework. Therefore, now we depend on the interface for service and not on the concrete type. This helps in writing a decoupled code which ultimately increases the testability and readability, reduces the code maintenance cost and makes it easy to understand and make changes in the code, etc. The Angular 2 framework has a dependency injection module, though this module is useful when the application grows bigger in scope. Thus, we can conclude the following benefits of the Dependency injection in Angular 2.

  • A Component can depend on Services via interfaces and not on concrete types.
  • By using Dependency injection module, it results into an application with decoupled code.
  • It increases the testability of the decoupled code.

The following is an example of an Angular 2 Dependency Injection that is used to inject the dependency where the data service is needed.

import { Injectable } from '@angular/core';
import { Employee } from './employee';
import { EMPLOYEES } from './mock-employees';

@Injectable()
export class EmployeeService {

  getEmployees(): Promise<Employee[]> {
    return Promise.resolve(EMPLOYEES);
  }
  getEmployee(id: number): Promise<Employee> {
  return this.getEmployees()
             .then(employees => employees.find(employee => employee.id === id));
	}
}

Explanation of employee.service.ts (typescript file)

  • When there are multiple components which access the same model data, then we cannot copy and paste the same code again and again. Instead of that, we should be creating a single data service that is reusable and can be easily injected into the components that require it.
  • Angular 2 has the Injectable Services as function that can be imported from ‘@angular/core’ package can be applied to the class as @Injectable () decorator as shown above.
  • In Angular 2, when the Typescript observes the @Injectable () decorator, then it emits metadata about that service. This Metadata may be required by the Angular2 in order to inject other dependencies into the service. In the above example, the service class has two methods ‘getEmployees ()’ and ‘getEmployee (id: number)’ which are used to return the array of employee objects and the employee object based on the employee id.

Property Bindings
Angular 2 framework uses the property bindings that help to automatically sync up the following.

  • The component tree with the model, and
  • The DOM with the component tree.
  • The Angular 2 framework uses zones that helps to know when to do it. In Angular 1, we have to inform the framework to run the check with the help of scope. $apply.

The following is an example of an Angular2 Property Binding where we are binding the click event to a method.
app/employee.ts (Model)

export class Employee {
  id: number;
  name: string;
}

app/employee.component.ts (Component)

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Employee } from './employee';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'my-employees',
  templateUrl: 'resource/employees.component.html',
  styleUrls:  ['assets/employees.component.css']
})

export class EmployeesComponent implements OnInit {
  employees: Employee[];
  selectedEmployee: Employee;
 
  constructor(
    private router: Router,
    private employeeService: EmployeeService) { }

  getEmployees(): void {
    this.employeeService.getEmployees().then(employees => this.employees = employees);
  }

  ngOnInit(): void {
    this.getEmployees();
  }

  onSelect(employee: Employee): void {
    this.selectedEmployee = employee;
  }

  gotoDetail(): void {
    this.router.navigate(['/detail', this.selectedEmployee.id]);
  }
}

resource/employees.component.html (template/DOM)

<h1>{{title}}</h1>
<h2>Our Employees</h2>
<ul class="employees">
	<li *ngFor="let employee of employees"
		[class.selected]="employee === selectedEmployee" (click)="onSelect(employee)">
		<div align="left">
		<span class="badge">{{employee.id}}</span>
		{{employee.name}}
	    </div>
	</li>
</ul>
<div *ngIf="selectedEmployee">
  <h2>
    {{selectedEmployee.name | uppercase}} is the Best Employee.
  </h2>
  <button (click)="gotoDetail()">View Details</button>
</div>
  • In the above example, employee.ts is a model class that has two attributes namely id and name of the employee.
  • Next is the employee.component.ts which has a component and the controller. The component has a selector as ‘my-employees’, template as ‘employees.component.html’, and style Urls as ‘employees.component.css’. The controller class ‘EmployeesComponent’ implements the ‘OnInit’ interface and we are using the data service ‘EmployeeService’ to get the employees data. This is nothing but the binding of the component with the modal class ‘Employee’.
  • Also, the controller class ‘EmployeesComponent’ has the number of methods. The method ‘onSelect (employee: Employee)’ and ‘gotoDetail ()’ are invoked on the (click) event from the template HTML code as shown above. This is the event binding of the DOM (Document Object Model) with the component.

Conclusion
In this article, we have covered the three core concepts of Angular 2 along with the Angular2 code samples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -