Getting familiar with components

Last time I mentioned that the Angular 2 tutorial teaches modularization of code. Actually it’s required by Angular itself to some extent. In order to add some behavior to HTML, we need to create components – Angular beings whose name is just self-descriptive. They are supposed to be reusable bricks which encapsulate some behavior and look the same in all places. The concept is the same as with user controls in ASP.NET Web Forms and WPF and partial views in ASP.NET MVC. Each component consists of a few parts:
– an HTML file with the component’s view
– a file with styles associated particularly with that view (this might be optional if global ones are sufficient)
– a component registration object which binds them together
– a class containing the component’s logic e.g. event handlers
In fact, it’s possible to include everything in one file (which is tempting especially when the HTML and styles are very short):

// Makes it possible to use @Component
import { Component } from '@angular/core';

// Registers a component
// A name for a custom HTML tag which will get this component's template as content
selector: 'my-test',
template: '
// Different parentheses here are required for a multiple lines value
styles: [`
h1 {
background-color: red;
color: white;
// Contains custom logic, must be exported in order to make it possible to use this component in other ones
export class TestComponent {

A VS Code extension “angular2-inline” provides even syntax highlighting, autocompletion and outlining for such views and styles specified in strings. But when some part is longer than the height of your monitor, it may become a nightmare to maintain such a component, sliding between different sections. So say a big no-no to having all-inclusive component definitions. It’s a good practice to separate them regardless of length of the inline strings, at least to keep the convention for easy navigation. So let’s make it all cleaner:

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

selector: 'my-test',
templateUrl: './test.html',
styleUrls: ['./test.css']

export class TestComponent {

It’s recommended to keep all the related files in the same directory. What happened here is that moduleId has been added – following advice from here (a blog written by some authors of Angular) I solved the problem of relative paths not working by default, which is well explained there.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s