Ang2

Building UI Functionality with Angular Components

Learn how to use components — the fundamental building block of Angular and the successor of ng-controller.

Eric Simons Up to date (Mar '19) Angular

In Angular, you no longer build your applications using ng-controller and views. Instead, you build your application using components — ideally these are tiny, reusable building blocks that are very similar to directives in AngularJS (and basically identical to the new component API in Angular 1.5).

A component is simply an Angular directive that includes a template.

Components are constructed in Typescript using Decorators. If you read a little bit into Decorators via the Typescript Handbook, you will see that it is nothing more than a function call that is passed a set of arguments prior to running the neighboring function/class.

The parameters passed into the decorator is what we call metadata. This information tells Angular a few things about our Component, such as:

  • What to import
  • Where to find the template
  • Where our styles exist
  • What to use as the selector
  • and more…

Under the hood, the component decorator is simply a class where the metadata is provided to the constructor method of some class. In short, the Component Metadata Class looks similar to the following:

@Component({
  selector: 'app-hero-list',
  templateUrl: './hero-list.component.html',
  providers: [HeroService]
})
export class HeroListComponent implements OnInit {
  /* . . . */
}

To get a well educated perspective, we heavily suggest reading the following resources on the subject:

Component Decorator via the Architecture Manual

In the next chapter, we'll explore a few of the API's that components expose to us before building out some real examples.