Learning

Component Custom Properties and Events

custom properties and events

This article on Component Custom Properties and Events is part of the Learning Angular series.

The app has been split into components and their children. Now it is needed to know how to pass the data in between them.

Binding to Custom Properties

Even when a property inside a class is public, the property can’t be directly accessed from outside (the components hosting it).
To make sure that they are accessible, add @Input() before the variable declaration.

@Input() element:ServerElement;

Make sure to import Input from @angular/core.
Now it an be bound like this:

<app-server-element *ngFor="let serverElement of serverElements" [element]="serverElement"></app-server-element>

Assigning an Alias to Custom Properties

An alias can be provided by updating the element definition as:

@Input('srvElement') element:ServerElement;

And can be used in the calling component as:

<app-server-element *ngFor="let serverElement of serverElements" [srvElement]="serverElement"></app-server-element>

Note: After using the above method, the ‘element’ can’t be used anymore and the ‘srvElement’ will only work.

Binding to Custom Events

To create a custom event:

serverAdded = new EventEmitter<{serverName:string, serverContent:string}>();

Defining a variable as an EventEmitter will make sure that the event can be emitted.
To make sure that it can accessed from outside, add the @Output() before declaration:

@Output() serverAdded = new EventEmitter<{serverName:string, serverContent:string}>();

And can emit by using:

this.serverAdded.emit({serverName: this.newServerName, serverContent: this.newServerContent});

Now it can be used as:

<app-cockpit (serverAdded)="onServerAdded($event)"></app-cockpit>

Assigning and Alias to Custom Events

Alias to be defined as:

@Output('srvAdded') serverAdded = new EventEmitter<{serverName:string, serverContent:string}>();

And to be used as:

<app-cockpit (srvAdded)="onServerAdded($event)"></app-cockpit>

All other information remains similar to Lecture 62.

Custom Property and Event Binding Summary

While the Input and Output declarations are easy to setup and data can be passed in between views, but when the views are very far linked, these Input/Output can become very difficult to manage.
In that case, services will come to play.

Leave a Reply

Your email address will not be published. Required fields are marked *