Angular 2 Component Input Output - lishman.io
lishman.io Loading..
Style: Blog or IDE

Angular 2 Component Input Output

Use property binding and the @Input decorator to pass data into a component, and @Output and EventEmitter to pass data out and bind to an event.

Last updated Dec 2016, Angular version 2.3.x

The Application

This is the application we are building. It allows the color of the box to be changed by setting the red, green and blue values in the input fields. It's a working application so go ahead and give it a try.

Loading...

The Components

The application consists of three types of component; ColorValueComponent allows the user to enter the color value in an input field, ColorBoxComponent displays the colored box (along with the red, green and blue values), and AppComponent acts as a container for the other components.

application components

Let's dive in and see how these components communicate with each other.

One-time String Initialization with @Input

We use one-time string initialization to pass a string constant into a child component, but only once during start up. Here we pass initial values to the label and init-value properties of the custom <color-value> element.

<color-value
    label="Blue"
    init-value="140"
    (value)="color.blue=$event">
</color-value>

This syntax only allows a string constant to be passed in and no change detection is performed.

To receive this value, the child component includes an @Input decorator on a property, as shown in the example below. Here, the label property is bound by matching the variable name, and the initialValue property is bound by matching the init-value alias in the @Input decorator.

export class ColorValueComponent implements OnInit {
    @Input() label: string;
    @Input("init-value") initialValue: string = "0";
    ...

The Application Code

Let's see how one-time initialization is used in our application, but first, take a look at this highlighting tip.

HighlightSource Code Highlighting

To quickly find the relevant code in the files below, click the show me link next to the Highlighticon and the important bits of the source code will be highlighted.

For example, Highlightshow me the @Component decorators in the source code below.

Click the link again to remove the highlight.

Now back to our application. We use one-time string initialization in the parent component to set the label property on the <color-value> element. This property matches the label variable in the child component which has been decorated with @Input. Highlightshow me the label property matching the variable name.

We do the same for init-value but this time we match the alias specified in the @Input decorator. Highlightshow me how the init-value property matches the alias.

app.component.ts x
Loading...
color-value.component.ts x
Loading...

Property Binding with @Input

Next we pass the red, green and blue color values to the <color-box> element like this:

<color-box [rgb]="color"></color-box>

This time however, we are using property binding and not one-time initialization. The square brackets bind the value in quotes to the rgb property of the <color-box> element. The value in quotes is no longer a string constant but a template expression which reads the color variable from the component class.

export class AppComponent {
    private color: RedGreenBlue = new RedGreenBlue();
}

When the color object changes, the rgb property is automatically updated by the property binding.

The Application Code

In our application, the color object on AppComponent is used in the template expression of the rgb property binding; whenever the color object changes, the rgb property is automatically updated too. Highlightshow me the color object in the property binding.

ColorBoxComponent uses the @Input decorator to identify the property to bind to. In this case the property name in square brackets is matched to the rgb alias in the @Input decorator. Highlightshow me the rgb property binding.

app.component.ts x
Loading...
color-box.component.ts x
Loading...

Event Binding with @Output

We can also pass values out of a child component back to the parent using an event binding. Let's see how.

In the child component we include an @Output decorator on a variable of type EventEmitter. This object will be used to fire our custom events.

@Output("value") colorValueEvent: EventEmitter<string> = new EventEmitter();

The value alias in the @Output decorator is the name of the event. If we omit the alias then the variable name is used instead (i.e. colorValueEvent). The <string> type in angle brackets is the data type of the payload to be sent with the event.

We trigger the event by calling the emit method on the EventEmitter object. This method takes one argument which is the payload of the event.

private sendColor(color: string): void {
    this.colorValueEvent.emit(color);
}

Back in the parent component we bind to this custom event by matching the name in parenthesis with the alias in the @Output decorator The payload is accessed using the built-in $event variable.

<color-value
    label="Blue"
    init-value="140"
    (value)="color.blue=$event">
</color-value>

The Application Code

Let's see how we use custom event binding in our application.

AppComponent binds to the value event on the <color-value> element. This matches the alias in the @Output decorator in ColorValueComponent. Highlightshow me the value event binding.

The colorValueEvent object is of type EventEmitter and, when the emit method is executed on this object, the event is triggered and the argument sent as the payload. The parent component accesses the payload using the built-in $event variable. Highlightshow me the emit method and how the payload is sent and received (in green).

app.component.ts x
Loading...
color-value.component.ts x
Loading...

Application Walk-through

Now let's step through the application to see how all the pieces fit together.

Quick Tip

You can use the symbol next to the source code to explore the project files.

Setting Values with One-time Initialization

AppComponent is the root component and co-ordinates the flow of data between the <color-value> and the <color-box> custom elements. Highlightshow me the custom elements in AppComponent.

From here, static string values are passed to the label and init-value properties of <color-value> using one-time string initialization. These values are then used in the template of ColorValueComponent which implements the <color-value> element. Highlightshow me how the label property is used. Highlightshow me how the init-value property is used.

Highlight Yellow shows how the property name is matched by the parent and child components.
Highlight Green shows where the variable is used in the template.

app.component.ts x
Loading...
color-value.component.ts x
Loading...

Passing Data Out of a Component with Event Binding

Let's take a closer look at ColorValueComponent which captures the value entered in a text field and sends it back to the parent component.

First we define the colorValueEvent property to be of type EventEmitter with a generic argument of string which identifies the type of the event payload. The value alias in the @Output decorator is the name of the event. Highlightshow me the colorValueEvent definition.

Highlight Yellow shows the name of the event. Highlight Green shows the type of the event payload.

So when the user changes a color value in the input field, the sendColor method is called on our class, and the emit method on colorValueEvent fires the event with the color value as the payload. Highlightshow me the sendColor method and how the color value is sent with the event.

In the parent component, we bind to this event and use the built-in $event variable to access the payload and update the color object in the template expression. Highlightshow me the event binding and how we use $event to access the payload.

Highlight Yellow shows the event binding. Highlight Green shows how the event payload is accessed.

color-value.component.ts x
Loading...

Passing Data In to a Component with Property Binding

We use a property binding on the <color-box> element to pass the red, green and blue values to ColorBoxComponent which implements the <color-box> element. The rgb property in square brackets in the parent component is matched to the @Input decorator alias of the redGreenBlue variable in the child component. Highlightshow me the property binding.

So now, whenever the color object is updated by the event binding on the <color-value> element, the redGreenBlue object in ColorBoxComponent is automatically updated by the property binding. Highlightshow me the color object in yellow and the redGreenBlue object in green.

app.component.ts x
Loading...
color-box.component.ts x
Loading...

Quick Tip

Remember you can click the symbol next to the source code to see other source files such as red-green-blue.ts which contains the RedGreenBlue class.

Where Next?

More Tutorials

To find out more about Angular components, check out these tutorials.

  • Templates - introduction to inline and external templates.
  • Interpolation - use curly braces and template expressions to output data.
  • Property Binding - update standard properties on the DOM using template expressions.
  • Event Binding - detect standard DOM events and execute template statements.
  • Two-way Binding - combine property and event binding to create two-way binding with ngModel.
  • Input Binding - bind to <input> fields such as text, textarea, checkbox, radio and select.
  • Built-in Directives - use ngIf, ngSwitch, ngFor, ngClass and ngStyle to transform the DOM.

Source Code

The source code for this tutorial is available in the angular-2-input-output GitHub repo.