Skip to content

Instantly share code, notes, and snippets.

@mhartington
Created November 16, 2015 18:50
Show Gist options
  • Save mhartington/3cdf4f7285c31ff802c7 to your computer and use it in GitHub Desktop.
Save mhartington/3cdf4f7285c31ff802c7 to your computer and use it in GitHub Desktop.
layout title edit_link tweet
default
Components
How to use components in Angular 2

Updated November 16, 2015

In Angular 2, Components are the main way we build and specify elements and logic on the page.

In Angular 1, we achieved this through directives, controllers, and scope. In Angular 2, all those concepts are combined into Components.

A simple component

Let's start with a very simple component that lists out our name:

import {Component} from 'angular2/angular2'

@Component({
  selector: 'my-component',
  inline: "<div>Hello my name is {{name}}. <button (click)="sayMyName()">Say my name</button></div>"
})
export class MyComponent {
  constructor() {
    this.name = 'Max'
  }
  sayMyName() {
    console.log('My name is', this.name)
  }
}

When we use the <my-component></my-component> tag in our HTML, this component will be created, our constructor called, and rendered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment