Angular guid
Input and Output in Angular
What for we need ‘Input’ and ‘Output’
The shortest description of what do “Input” and “Output” is showed on picture.
We have 2 components “Main component” and inner component “Child component”. “Input” and “Output” are defined in “Child component”. Sometimes we need to put information or object for initialization in “Child component” for that purpose we use “Input“.
Basically it the way how Angular share data between components.
To better understand it we need to make an example of input and output in Angular.
Imagine that “Child component” have a button when user clicked on that button “Main component” must know that, for that purpose we use “Output“. So if “Child component” contain element which value can be changed or we need to notify about something “Main component” we used “Output“.
Let take a close look on code.
“Main component” contain input which is bind to property “childTitle” and this property we put in “Child component” notice that we use Input decorator. Let’s change title of “Child component” dynamically that is why we will use two-way binding in “Main component” — [(ngModel)], for “ngModel” we need to to add “FormsModule” in import section in AppModule.
In Html of “Main component” on line 8 we created input attribute [title] (property in “Child component”), as an input value we use “childTitle” (property in “Main component”). That how we bind child and parent component using Angular input decorator.
In “Child component” I used getter and setter because I wanted to show you how we can find moment when component receive data, in setter we can define some action which we need.
Now let use Angular Output decorator.
“Child component” now contains button, click is bind to “countChange” method and main part is EventEmitter “onChange” which we call when user clicked on button, that how “Main component” will be notified. In EventEmitter we could pass a parameter it could be anything string or our class, in our case it will be a count number.
EventEmitter in Angular is a type of subscription. EventEmitter helps us to notify other component about some changes.
Also we need to change a little bit “Main component”. We need to create method which will be notified and bind it to event emitter in “Child component” for that purpose we create method “onCountChanged” with parameter and in HTML file we wrote this bind relationship.
That how we use “Input” and “Output” in Angular. You can download this example on my GitHub repository.
Originally published at tomorrowmeannever.wordpress.com on February 16, 2019.