AngularCli – Passing Data In / Out of Angular2 Components
In this post how we can pass data in and out of an angular2 component. Here we are creating an app to increment the input number. We have a textbox to enter a number. We are also creating a component. The number entered in the textbox is supposed to be passed to the component. Clicking the component should increment the number and the data should be passed from the component to outside.
Let’s first create an angular2 app using Angular-Cli. Let’s name it Angular2PassingData.
ng new Angular2PassingData
Now let’s create a component incrementer.
ng generate component incrementer
The new component is a simple component with just a button. As the button is clicked, increment() method is called for the component.
AngularCli has also generated incrementer.component.ts. Since we are planning to pass data in and out, so let’s import Input and Output from @angular/core. We also need to import EventEmitter from the same package which is to be used for the Output.
We have decorated inputNum and @Input and incremented as @Output. The inputNum has number type. The incremented is an EventEmitter to be used to emit output data through events.
In app.component, we have a textbox to enter a number. We are binding incrementInputNum property from component’s code behind to the textbox. We are binding another property incrementInputNum to incrementer.component’s inputNum property. Additionally, the incremented event from incrementer.component would trigger increment method to be called with event’s data. We also see another property being used here, which is incrementedNum, which is just displayed in a label. It would show the incremented number in the user interface.
As we have seen above, we are expecting two number based properties in app.component’s code behind. They are incrementInputNum and incrementedNum. In the incrementNum() method, we are just assigning the data from the event to incrementedNum property.
Now let’s run the application using ng serve. The app runs on localhost:4200 by default. As we enter a number and click Increment button, the data is passed to the incrementer component. It is incremented there and an event is emitted. The app.component is subscribing to that event and updates its own variable, which is then shown on the UI.
Assigning event data in template
Now let’s try to make it a little simpler. We are simply assigning the event’s data to one of the property in app.component’s code behind (other than writing to the console). Angular2 can make it a little easier for us. We can make it simpler by directly assigning the event’s data the property. Here we are updating incrementedNum to the data emitted by the component’s incremented event.