Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Angular 4 Tutorial : Custom Data Bindings

Hello everyone, as we know, we have learned some basics of Angular, in my last post, http://mytechthinking.in/2017/08/26/angular-4-tutorial-understanding-the-data-bindings/, we saw how data bindings in angular works. Now we know how the template can communicate with the business logic. But in modular programming it is important that the modules should interact with each other, in here we have components. So it is important that the components should be able to interact with each other. So let’s check that out via some examples. In this example, I’ll be using the Angular material for designing as we don’t want o focus on how it looks but on how it works. So for that let’s install the Angular material packages.

npm install --save @angular/material @angular/animations

Now let’s add an Angular material theme to style.css file

@import '[email protected]/material/prebuilt-themes/indigo-pink.css';

I have created an example which looks like below screenshot. We have two buttons to add the text of either colour. Example-UI-1

In this, I have created two components (one for Input field and second for displaying text ) so that we can see how to interact with the components. So first let see what are the components and then I’ll explain how it works.

App Component:
Html:



TypeScript:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  colorArray = [{color: 'pink', content: 'I am pink!'}];
  onPinkAdded(inputText: {content: string}) {
    this.colorArray.push({color:  'pink' , content: inputText.content});
  }
  onIndigoAdded(inputText: {content: string}) {
    this.colorArray.push({color:  'indigo' , content: inputText.content});
  }
}
Input-Form Component:
Html:
  Add Pink and Indigo Color text            

TypeScript:

import { Component, OnInit, EventEmitter, Output} from '@angular/core';
@Component({
  selector: 'app-input-form',
  templateUrl: './input-form.component.html',
  styleUrls: ['./input-form.component.css']
})
export class InputFormComponent implements OnInit {
  @Output() onPinkClick = new EventEmitter();
  @Output() onIndigoClick =  new EventEmitter();
  newContent = '';
  constructor() { }
  onAddPink() {
    this.onPinkClick.emit({content: this.newContent});
  }
  onAddIndigo() {
    this.onIndigoClick.emit({content: this.newContent});
  }
  ngOnInit() {
  }
}
Display Component:
Html:

    
      {{colorElement.color}}
    
      
        {{ colorElement.content }}
        {{ colorElement.content }}
      
    
  

TypeScript:

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.scss']
})
export class DisplayComponent implements OnInit {
@Input() colorElement: {color: string, content: string};
  constructor() { }
  ngOnInit() {
  }
}

Here we see that we have one parent component i.e. the App component and its two child components i.e. Display component and Input-Form component. Input-Form component contains the fields to get the input from the user, whereas Display component displays the entered values. The App component act as a medium to communicate between the components. Here we have used two directives @Input and @Output to enable the communication.

Input Directive (Custom Property Binding)

The one part of the requirement here is that the elements of colorArray should be iterate and passed to display component from the app component. To achieve that, i.e. passing the object from the parent to child component we have used property binding. In the app component template,

 

we have set the color object to colorElement property of display component. And in display component, we have created a colorElement property of the desired type. But by default, the component properties are accessible to its class only and is not visible to other components. To make that property visible Angular provides @Input() directive from angular/core. The @Input directive makes property accessible from other components and lets other components change its value. Like in display component we have done.

@Input() colorElement: {color: string, content: string};

We can assign an alias to the properties with input directive. So now the above code can be written as:

@Input('colorObject') colorElement: {color: string, content: string};

Now in app component, we can access the property by using colorObject and not by colorElement.

Output Directive (Custom Event Binding)

Now we can display elements from the colorArray, but still, we cannot add user input to the array. In order to that, we need to send data from the child to parent. To do that first we need to bind the click event of buttons and set the input value to some property in the input-form component.


  

Now we need to throw the input values so that the other component can listen to it.

@Output() onPinkClick = new EventEmitter();
  @Output() onIndigoClick =  new EventEmitter();
  newContent = '';
  onAddPink() {
    this.onPinkClick.emit({content: this.newContent});
  }
  onAddIndigo() {
    this.onIndigoClick.emit({content: this.newContent});
  }

Here as you can see I have created three properties, newContent property holds the input data, whereas the other two are the object of EventEmitter type. The EventEmitter object is given by Angular to create a custom event. EventEmitter creates an event which can be listened by the other components. It gives an emit method which throws the object passed on the occurrence of the particular event. It is of generic type so we can set the object type in diamond brackets to throw that event object.  In this example, we have created two EventEmitter object onPinkClick and onInidgoClick which are emitted on click of the respective button.

But to make these events visible to other components we use @Output directive of angular/core. So now we can access this custom-created event from app component.


Please see that we are passing $event property to the method, this is because we need to access the object emitted by the input-form component. Which we are accessing in the respective methods.
onPinkAdded(inputText: {content: string}) {
    this.colorArray.push({color:  'pink' , content: inputText.content});
  }
  onIndigoAdded(inputText: {content: string}) {
    this.colorArray.push({color:  'indigo' , content: inputText.content});
  }

So in this post, we learned how to communicate between components using the custom data bindings.


This post first appeared on Mytechthinking.in, please read the originial post: here

Share the post

Angular 4 Tutorial : Custom Data Bindings

×

Subscribe to Mytechthinking.in

Get updates delivered right to your inbox!

Thank you for your subscription

×