Twitter LogoFacebook Logo
Understanding Inputs and Ouputs
Inputs and Outputs in Angular
By: King

One of the major advantages of building applications using Angular is the ability to divide our application into tiny modules call components. 

But how can we control the behavior of a component from the outside? And how can we react to the changes made by the component? We need a way to insert and extract information from our components so we can interact with them.

Take a look at this scenario:

Image from Codeible.com

We have a component that displays some text. If we want to reuse the component, it will display the same thing and behave the same way. This is an unwanted behavior. Whenever we want to reuse a component, we want to be able to control its behavior so that it behaves differently than other components of the same type or simply, to display a different message instead of the same thing over and over again. 


In Angular, we can give our components entry points to establish a connection with the outside. These entry points are known as inputs and outputs. Inputs are used to receive information from the outside and outputs are used to release information from the inside.

Image from Codeible.com

Let’s start by doing some examples.


Open your Angular project. Create a component using the ng generate component command

ng generate component Greeting

Upon completion of the command, expand the component folder and go in the component TypeScript file.


To begin adding inputs to our component, we have to add Input to our imports.

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

Then declare an input receiver variable with the type of input it can receive. The purpose of the input receiver is to receive and store the value that is passed into the component. Lastly, add a @Input() decorator as part of the variable declaration to indicate that the variable is used as an input receiver. That is all we have to do to add an input.

@Input() name: string;

So now, we have an entry point where we can pass a string into our component from the outside. It is a string because the type of our input receiver is a string. It can be anything. A Boolean, a number, a class, and so on. 


To show how this works, go to the component HTML page and use interpolation to place the variable in the page. 

<p>{{name}}</p>

Now add the component to the app component html page so it will be rendered on to the screen. Go to the component TypeScript file and get the value of the selector property from the component decorator.

@Component({
  selector: 'app-greeting',
  templateUrl: './greeting.component.html',
  styleUrls: ['./greeting.component.css']
})

Then go to the app component html page and add the component. 

<app-greeting></app-greeting>

Next, we will insert a string into the component.  Go to the app component TypeScript file. Declare a string variable and assign it some text. 

insert = "King";

Go back to the app component HTML page and insert the variable into the component. To access the inputs of a component, we use the square bracket syntax and then provide the name of the input we want to access, which is the name we have given the input receiver. Then we specify what we want to insert.  We want to insert our variable.

<app-greeting [name]="insert"></app-greeting>

So right now, our component should display - King. Let’s verify that. Save the project and start the local server. Open the browser and go to localhost:4200.


As you can see, by adding inputs to our component, we can insert anything into our components and control the behavior from the outside.

Now, let’s talk about outputs. 

Outputs are custom events that we can add to our components.
 
Imagine a clinical setting. When you go into a clinic, you will first sign in and register your information. This is the input process. You are inputting your information so the clinic can compile the information and add you to the queue. Then you will sit and wait for your name to be called. When it is time for the clinic to call for the next patient to see the doctor, they will call a name and you will listen to see if your name is called. You are subscribed to their system. 

Image from Codeible.com

This is the purpose of outputs. When you add an output, you are adding a system where things from outside of the component can subscribe  and listen to whatever the component have to say. Then they can choose to react to it or not.

Let’s see how we can add outputs.

Go back to VS Code. Go to the component TypeScript file add Output and EventEmitter to our imports. 

import { Output, EventEmitter } from '@angular/core';

Then declare an output variable. The role of the variable is to store an EventEmitter object. This object will turn our output variable into an event node where things can subscribe to it and listen to our component. Inside the angle brackets is the type of information it can broadcast. Lastly, add the @Output() decorator in to the variable declaration to indicate that the variable is an output. 

@Output() sendMessage = new EventEmitter<string>();

So now, we have an output that can broadcast a string value to the outside. But we are not done. We need to define when to trigger our event node to broadcast the information and what information we want to broadcast.


Let’s say that we want to send a greeting message out using the name input we are taking in when we click on a button. 

So, our WHEN will be when we click on a button, and our WHAT is the greeting message. 

Go to the Greeting component HTML page. Add the button and attach a click event. Then assign a function for it to call. 

<button (click)="send()">Send Message</button>

Go to the component TypeScript file and define the function.


In the body of the function, we will specify what to broadcast. The EventEmitter objects has an method call emit(). It takes in an argument, and that is the information you want to release to the public. Since our EventEmitter object can broadcast strings, we pass in a string. If it were Boolean, we would pass a Boolean, and if it were a object, we would pass in an object, and so on. The purpose of the emit() method is to trigger our event node to broadcast the information.

send(){

   this.sendMessage.emit(`Welcome ${this.name}!`);
}

Now the output is complete. We can subscribe to it.

Go back to the app component HTML page. To access the outputs on a component, we use the parenthesis and then provide the name of the output we want to subscribe to. Then we assign a handler function to handle the event. 

<app-greeting 

   [name]="insert"
   (sendMessage)="onMessageReceived()"
></app-greeting>

Go to the app component TypeScript file and define the function.

onMessageReceived(){

   alert("Message Received");
}

Right now, when we click on the button in the Greeting component, it will trigger the output event and call this handler function.


Let’s verify that. Save the project and go to the browser. Click on the button. 

As you can see, we added a custom event to our component that we can handle. You may be curious what happened to our greeting message that it supposed to broadcast. 

Since outputs are really events, when they are triggered, they return an $event object that has the information for the event. We can use that event object that is returned to us and pass it into the function that it is calling and get the broadcast information. Here is what I mean.

Go back to VS Code and then go to the app component html page. The custom output event will return an $event object when it gets fired. So, we can then pass that object into our function and get the message.

<app-greeting 

   [name]="insert"
   (sendMessage)="onMessageReceived($event)"
></app-greeting>

However, we need to make the function accept that object. Go back to the app component TypeScript file and locate the function definition, add a parameter to accept that $event object as an argument.

The event object is the message itself. When we use the emit() method, it will make the $event object take the form of the value that was passed in the method. Since we passed in a string, the $event object becomes a string. So, we can just get the message by getting the $event object. 

onMessageReceived(event: string){

   let message = event;
   alert(message);
}

Save the project and go to the browser. Click on the button. 


As you can see, we brought a value from inside the component out so we can use it outside of the component.

Recap

Let’s take a moment to recap what we have learned.

1. We learned that we can add inputs and outputs to our components. We use inputs to insert values into a component and outputs to get values out from the component.

2. We learned how to add inputs and outputs to our components.

To add inputs, we need to add Input to the imports and then add the @Input() decorator to the input receiver variable.

To add outputs, we need to add Output and EventEmitter to the imports and then add the @Output decorator to the output variable. Then we have to initialize the output variable with an EventEmitter object.

3. We learned that outputs are really events and that they can be triggered by calling the emit() method. 

4. We learned that events returns an $event object that contains information about the event. We can use the $event object that is returned to us to get the value that was passed in the emit() method.

5. We learned that if we want to access an input, we use the square bracket syntax and provide the input we want to access inside. Then we assign a value to insert.

6. We also learned that if we want to access an output event, we use the parenthesis and provide the event we want to access. Then we assign a handler function to handle the event.


Sign In