Getting started with Angular 2 requires three major files.

  • app.component.ts: The main component that encompasses our entire app.
  • app.module.ts: The top level module for our app. The module defines a certain section of our site. In this case, our entire site is the module.
  • main.ts: This is where we bootstrap our app. This is similar to using ng-app in Angular 1.

The reason we separate bootstrapping out into its own file is that we could bootstrap a number of different ways. We're going to bootstrap our app for the browser, but it could be done for mobile, universal, and more.

Modules

@NgModule is the decorator that gives us an Angular 2 module. Angular 2 module's are the way that we can bundle sections of our applications into a singular focused package.

A module can include many parts including other modules (imports), components and/or directives (declarations), and services used to access data (providers).

Modules are defined using:

  • imports: Other modules (either Angular 2 or custom built) that are also bundled parts of our application
  • declarations: These are any components or declarations that you want access to in your application
  • providers: These are services and used as a singular place to access and manipulate certain data. ie a UserService to hit a user API

Bootstrapping

The top level module will use the bootstrap attribute to tell the module what to use when creating our app. The style guide and conventions prefers to use an AppComponent as the top level of our app.

The Files

app.component.ts

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

@Component({
  selector: 'my-app',
  template: `
    <div class="jumbotron">
      <h1>Welcome to Our App!</h1>
    </div>
  `,
  styles: [`
    .jumbotron { box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2); }
  `]
})
export class AppComponent {}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  imports: [ BrowserModule
],
  declarations: [ AppComponent
],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

Chris Sevilleja

162 posts

Co-founder of Scotch.io. Slapping the keyboard until something good happens.