Creating an Angular 2 component

An Angular 2 component (written using TypeScript) is a class with the @Component decorator/attribute.

For example

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

@Component({
   // metadata properties
})
export class MyComponent {
   // methods, fields etc.
}

In it’s simplest form we might just supply an inline template to the metadata properties, to define the component’s HTML. Although we can create multiline HTML encased in back ticks `<multiple line HTML>`. We can also store the HTML in a separate file and reference it using templateUrl. Let’s look at some examples.

Single line HTML

@Component({
   template: '<p>Hello</p>'
})
// class definition

Multiline HTML (using the backtick)

The backtick ` is used for multiline strings.

@Component({
   template: `
   <p>Hello</p>
   <p>World</p>
   `
})
// class definition

External Template HTML

@Component({
   templateUrl: 'my-template.html'
})
// class definition

Ofcourse, the equivalent of an HTML component wouldn’t be so useful if we couldn’t also define styles. So, as you’d expect we also have the metadata property for style that works in the same way as the template.

The main thing to note is that the stylesUrls is plural and expects and array of styles, i.e.

@Component({
  selector: 'my-app',
  templateUrl: 'my-app.html',
  styleUrls: ['my-app1.css', 'my-app2.css']
})
// class definition

Referring to class fields

At this point, the class itself might seem a little pointless, but by adding fields etc. to it we can reference these from the @Component template itself.

For example

@Component({
   template: '<p>{{greeting}}</p>'
})
export class MyComponent {
   greeting: string = 'Hello';
}

The {{ }} is Angular 2’s expression syntax, meaning it can contain code to access fields, or actual expressions, such as 2 + 3 or method calls such as max(a, b).