Angular 2 Custom Component Example – TypeScript

After the very basic “Hello World” example, let’s take another step forward to see what an custom component looks like in Angular 2. The version of Angular 2 used in this example is 2 2.0.0-beta.0. Would like to see javascript version of this example?

 

In this tutorial, we will create a custom component with input and output using Angular 2 in TypeScript. The custom component we will be creating here is a custom input that takes inputs such as label and value, and fires a change event when the input is changed. We will also implement a change detection here using event. I will create a separate post to talk about change detection and two way binding later.

 

Once created, the usage of the custom input will be like

 

Below is the output of this example.

custom input screenshot

So, let’s get started.

 

Folder Structure

This is the folder structure of this example. Source code is also available here.

Angular 2 Custom Component example code folder structure

boot.ts

Similar to examples, we will still use this  boot.ts file to bootstrap our application.

app.component.ts

This is our app component. It is really the top-level component in this example. As you may notice, there are new things here. Please see the details inline.

app.component.tpl.html

This is the template file of the app component. In this template, we use the <custom-input/> element and also capture the input value and display it on the bottom. As you can see, we

  • pass a string “Name” to the label  property,
  • bind value  property to person.name,
  • and we also bind the valueChanged  event to the event handler onValueChanged .

custom-input.component.ts

Here is our custom input component. This component has 2 inputs and 1 output. The event handler onInputChange (bind to keyup event. You will see this in the template file) will in turn emit valueChanged  event with the new value whenever it is triggered.

custom-input.component.tpl.html

This is the template of the custom input component.

index.html

Finally, this is the index.html that wires all things up.

 

At this point, you should be able to create a custom component with input and output. The source code of this example is also available here for download.

 

Resources


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.
  • Lars Jeppesen

    Great stuff, thanks