Angular 2: Components

Sara Gee
2 min readMay 30, 2016

--

In this Angular 2 series, I will go over the basics of Angular 2 and how to get started to build a simple phone book. The best starter guide is to clone this repo: https://github.com/angular/quickstart. In this first part, let’s focus on components and getting a few words up. You will use components… a lot! TypeScript is the preferred programming language for Angular 2.

Components

A Component is a class that encases the template, data binding, and logic of the view. Components are powerful because they are reusable. Templates include directives and additional injected components. Injection of components within templates increases modularity of the codebase and data binding controls the flow of data from component to template.

index.jsimport {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
bootstrap(AppComponent);

Bootstrapping AppComponent defines the component as the parent of our application — it also can connect various routes which we’ll get into later.

app.component.tsimport {Component} from '@angular/core';@Component({
selector: 'app',
template: '<h1> Phone Book </h1>'
})
export class AppComponent { }

Plucking {Component} from our angular module allows us to access the Component Decorator. The component decorator enables us to attach metadata to the decorators that allows Angular to process a Class.

Metadata is “data that provides information about other data”. — wikipedia

To invoke the component decorator, an object must be provided with config options. Config options include: selector, template, providers, directives, pipes, and styles.

index.html (provided in the starter guide)<html>
<head>
<title>Phone Book</title>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial- scale=1">
<link rel=”stylesheet” href=”styles.css”>
<! —- Polyfill(s) for older browsers -->
<script src=”node_modules/core-js/client/shim.min.js”></script>
<script src=”node_modules/zone.js/dist/zone.js”></script>
<script src=”node_modules/reflect-metadata/Reflect.js”></script>
<script src=”node_modules/systemjs/dist/system.src.js”></script>
<script src=”systemjs.config.js”></script>
<script>
System.import(‘app’).catch(function(err){ console.error(err); });
</script>
</head>
<body>
<app> Loading... </app>
</body>
</html>

The selector <app> that is defined in the component decorator is injected into the DOM. Below, you can see that our template from the AppComponent is rendered.

A basic phone book we will build— each orange bordered box represents a component.

The big picture:

https://angular.io/docs/ts/latest/guide/architecture.html

--

--