a blog for those who code

Monday, 21 January 2019

Custom Bindings using Input and Output Properties in Angular 7

In this post we will be learning about Custom Property Bindings using Input property and Custom Event Bindings using Output property. Just to get started we should know that all properties of a Component are only accessible inside the Component and not from outside. Thus you need to explicitly defined which property you need to expose to the outside world of components, which then can be accessible from outside.



Input Property & Custom Property Bindings


An Input property is a settable property where the values flow into that property from other components when it's data is bound with a property bindings. We can always bind to a public property of a component in its own template for that we do not need Input properties, this is needed when we are bind to a property of a different component.

For Example : In an AppComponent template we want to bind a property to MyComponent whose selector is app-my-component.


<app-my-component [myName]="nameOfComponent"></app-my-component>

Now since myName is not a public property, Angular will throw an error like below

Uncaught Error: Template parse errors:
Can't bind to 'myName' since it isn't a known property of 'app-my-component'

It is because, Angular compiler will not bind the properties of a different component if they are not specied as Input or Output properties. So when we specift myName as an Input property as shown below, then using myName in the parent component as the property will not throw any error.

import { Input } from '@angular/core'
@Input() myName: {a: string, b: string};

We can also give different name to my Input properties as shown below, where instead of using myName as a property we use name as a property.

@Input('name') myName: {a: string, b: string};

Output Property & Custom Events Bindings


An Output property is an observable property which always returns an Angular EventEmitter where the values flows out of the component. That means in a simple way letting the parent component know that something has changed in the child component.

import { Output } from '@angular/core'
@Output() myEvent = new EventEmitter<{a: string, b: string}>();

So myEvent is an output property and myEventCreated is a function which will emit those events.

<app-my-component (myEvent)="myEventCreated($event)"></app-my-component>

Just like Input, we can also give different name to my output properties as shown below, where instead of using myEvent as a event property we can use myOnlyEvent as a property.

@Output('myOnlyEvent') myEvent = new EventEmitter<{a: string, b: string}>();

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a comment