Design a site like this with WordPress.com
Get started

Angular JS Data Binding

One-way binding does below things:

  1. Angular js provide one way data binding when you use [] symbol with property or when you use interpolation .data is getting passed from view to component and from component to view.

In One way binding if user change anything in child component andonly one way communication is established with variable then that value wont get reflected in parent

Below are some examples

Two-way binding does two things:

  1. Sets a specific element property.
  2. Listens for an element change event.

Below are some examples

In Angular JS two way data binding is denoted by [()] its also called banana sign.

This is combination of property binding “[]” and event binding “()”

Two way binding helps user to setup communication between component to view and view to componetn so its bi directional communicaiton that will help user.

This will be useful when user changes anything in child component and that value needs to be reflected in parent component .

In Angular formmodule ngModel will provide two binding between component and view .

In todays example we will see One way and Two way data binding with Ng Model

In this Example we will use color to demonstrate how one way and two binding can be achieved with ng-Model

  1. Create your AngularJs Application

Please follow steps mentioned in below post

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

2. Create Child Component

ng generate component twowaybindingwithngmodel

3. Edit twowaybindingwith-ngmodel.component.ts

In this component we have declared variables to demonstrate one way and two way binding initially both will have red color

When user will click button it will log color and we will see if it reflects in console as per change.

twowaybindingwith-ngmodel.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-twowaybindingwith-ngmodel',
  templateUrl: './twowaybindingwith-ngmodel.component.html',
  styleUrls: ['./twowaybindingwith-ngmodel.component.css']
})
export class TwowaybindingwithNGModelComponent implements OnInit {

  twowaycolor = 'red';
  onewaycolor = 'yellow';
  constructor() { }

  ngOnInit() {
  }

  click() {
    console.log('Two way color:' + this.twowaycolor);
  }

  clickme() {
    console.log('One way color:' + this.onewaycolor);
  }
}



4. Edit HTML File twowaybindingwith-ngmodel.component.html

Here we are adding button which will be get clicked to print color on console.

IN first block we have used two way binding with

Enter Color  : <input [(ngModel)] ='twowaycolor'> 

And in second blod we are using it for one way data binding

 Enter Color  : <input [ngModel] ='onewaycolor'> 

When in first block twowaycolor value get changed and will click button it will be get printed because data will be get passed from component to view and view to Component in bi-direction.

When in second block onewaycolor value get changed and will click button it will be print old value because new value from view is not getting passed to component as its using unidirectional data binding with [ngModel

twowaybindingwith-ngmodel.component.html

<p>One and Two way Binding with NG Model</p>
<div class="card-panel   blue ">
    <h2>Two way Binding</h2>
    Enter Color : <input [(ngModel)]='twowaycolor'>
    <br>
    Color value is: {{twowaycolor}}

    <br>
    <button (click)="click()"> CLickme</button>


</div>
<div class="card-panel   blue lighten-3">
    <h2>One way Binding</h2>
    Enter Color : <input [ngModel]='onewaycolor'>
    <br>
    Color value is: {{onewaycolor}}

    <br>
    <button (click)="clickme()"> CLickme</button>
</div>






Ng Model need to declare form module in app.module.ts else it will give you error .Kindly add FormsModule in app.module.ts so kindly add like below code base

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TwowaybindingwithNGModelComponent } from './twowaybindingwith-ngmodel/twowaybindingwith-ngmodel.component';
import { FormsModule } from '@angular/forms';
import { NgclassandngstyleComponent } from './ngclassandngstyle/ngclassandngstyle.component';

@NgModule({
  declarations: [
    AppComponent,
    TwowaybindingwithNGModelComponent,
    NgclassandngstyleComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

5. Add Materialize css in index.html

In Index.html we will add materialize css and js file to use elegant UI

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularJSTwoWayDataBanding</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
       
</head>
<body>
  <app-root></app-root>
</body>
</html>

6. Edit app.component.ts : This is parent component

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'AngularJSInBuiltDirectives';

}



7. Edit app.component.html

We have added ngmodel component in app.component.html

app.component.html

<div class="card-panel   blue lighten-3">
    <app-twowaybindingwith-ngmodel></app-twowaybindingwith-ngmodel>
    
    </div>




8. Run Application

If you clone entire project then first run npm install so all dependencies will get downloaded.

Then run below command

ng serve --open

You will get below kind of output for your project once it get compiled and it will open your application in browser

9. Check Outpput

go to http://localhost:4200 path in browser

We need to enter new color in text box

After editing color in both input boxes. Change only reflected in first color and not in second one that says first one is having two way data binding and second one is having one way data binding.

Now we will click on button to check value in component.

Below screenshot displays One and Two way data binding between variables using ng model

This example demonstrated that v ng-Model can be used for one and two way binding.

Source Code:https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives

Angular JS Two way Data Binding with combination of property binding and an event binding

Basics of two-way binding

Two-way binding does two things:

  1. Sets a specific element property.
  2. Listens for an element change event.

In Angular JS two way data binding is denoted by [()] its also called banana sign.

This is combination of property binding “[]” and event binding “()”

Two way binding helps user to setup communication between component to view and view to componetn so its bi directional communicaiton that will help user.

This will be useful when user changes anything in child component and that value needs to be reflected in parent component .

In Angular formmodule ngModel will provide two binding between component and view .

In todays example we will see Two way binding between Angularjs child and parent component.

Here we will use property binding and event binding separately

This binding syntax is really just syntactic sugar for a property binding and an event binding.

In this Example we will pass color from parent to child while intantiation and then change color form child .

When color in child element get changed it should get reflected in parent component

  1. Create your AngularJs Application

Please follow steps mentioned in below post

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

2. Create Child Component

ng generate component twowaypropertychange

3. Edit twowaypropertychange.component.ts

In this component we have declared one input varibale in which we will get value from parent component and we will modify that variable and same will be get passed to parent using output event.

Kindly use below naming convention for input and output .keep same name as prefix( e.g. childcolor) and then ass suffix as Change to it.

Here when function is changing value we are emitting same value to parent variable by passing child elements input variable back.

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';


@Component({
  selector: 'app-twowaypropertychange',
  templateUrl: './twowaypropertychange.component.html',
  styleUrls: ['./twowaypropertychange.component.css']
})
export class TwowaypropertychangeComponent  {

  @Input()
  childcolor: string;

  @Output()
  childcolorChange = new EventEmitter<string>();


  change()  {
this.childcolor = 'green';
this.childcolorChange.emit(this.childcolor);
  }


}

4. Edit HTML File twowaypropertychange.component.html

Here we are adding button which will be get clicked to change color and change() function will get called.

We are using childcolor variable to assign to color style

</blockquote>
<h4>Child Color:{{childcolor}}</h4>
<br>

<button class="btn waves-effect waves-light"  (click)="change()">Change to Green</button>
<h1 [(style.color)]="childcolor" > Twoway Child</h1>



5. Add Materialize css in index.html

In Index.html we will add materialize css and js file to use elegant UI

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularJSTwoWayDataBanding</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
       
</head>
<body>
  <app-root></app-root>
</body>
</html>

6. Edit app.component.ts : This is parent component

In Parent we have declared variable and initial color will be red.

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  title = 'AngularJSTwoWayDataBanding';


  parentcolor = 'red';

}



7. Edit app.component.html

Whenever you will use child component you have to use child input variable which need two way binding in [()] and pass parent property for which you want two way binding. like below screenshot

<div class="card-panel   blue lighten-3">
  <h3>One Way Data Binding with  Parent Child</h3>
<app-onewaybinding [childcolor]="parentcolor"></app-onewaybinding>

<h4>Parent Color:{{parentcolor}}</h4>
<h3 [style.color]="parentcolor" > Parent Component</h3>
</div>

<div class="card-panel   blue lighten-3">
  <h3>Two Way Data Binding with  Parent Child</h3>
<app-twowaypropertychange [(childcolor)]="parentcolor"></app-twowaypropertychange>

<h4>Parent Color:{{parentcolor}}</h4>
<h3 [style.color]="parentcolor" > Parent Component</h3>
</div>


<div class="card-panel   blue lighten-3">
  <h3>Two Way Data Binding with combination of   Parent Child Using [] property binding  and () event binding </h3>

<app-twowaypropertychange [childcolor]="fontSizePx" (childcolorChange)="parentcolor=$event"></app-twowaypropertychange>
<h4>Parent Color:{{parentcolor}}</h4>
<h3 [style.color]="parentcolor" > Parent Component</h3>
</div>




For this example we will just use below code snippet to understand it

<div class="card-panel   blue lighten-3">
  <h3>Two Way Data Binding with combination of   Parent Child Using [] property binding  and () event binding </h3>

<app-sizer [childcolor]="fontSizePx" (childcolorChange)="parentcolor=$event"><div class="card-panel   blue lighten-3">
  <h3>Two Way Data Binding with combination of   Parent Child Using [] property binding  and () event binding </h3>

<app-twowaypropertychange [childcolor]="fontSizePx" (childcolorChange)="parentcolor=$event"></app-twowaypropertychange>
<h4>Parent Color:{{parentcolor}}</h4>
<h3 [style.color]="parentcolor" > Parent Component</h3>
</div>

The $event variable contains the payload of the TwowaypropertychangeComponent.childcolorChange event. Angular assigns the $event value to the AppComponent.parentcolor when the user clicks the buttons so data will be passed from child to parent and vice versa

Two way Data Binding with combination of property binding and an event binding

8. Run Application

If you clone entire project then first run npm install so all dependencies will get downloaded.

Then run below command

ng serve --open

You will get below kind of output for your project once it get compiled and it will open your application in browser

9. Check Outpput

go to http://localhost:4200 path in browser

We have set up red color in parent and passed same in child

We need to click change to green button so we will see data change between parent and child

After clicking button you will get below output

This example demonstrated that value can be passed form parent component to child but if child modifies this value it will be reflected in parent as its used two way data binding. Changed value will be emitted by child and same will b e get reflected in parent by angularjs. This way you can establish bidirectional communication between parent and child.

Source Code:https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSTwoWayDataBanding

Angular JS Data Binding with ngModel

One-way binding does below things:

  1. Angular js provide one way data binding when you use [] symbol with property or when you use interpolation .data is getting passed from view to component and from component to view.

In One way binding if user change anything in child component andonly one way communication is established with variable then that value wont get reflected in parent

Two-way binding does two things:

  1. Sets a specific element property.
  2. Listens for an element change event.

In Angular JS two way data binding is denoted by [()] its also called banana sign.

This is combination of property binding “[]” and event binding “()”

Two way binding helps user to setup communication between component to view and view to componetn so its bi directional communicaiton that will help user.

This will be useful when user changes anything in child component and that value needs to be reflected in parent component .

In Angular formmodule ngModel will provide two binding between component and view .

In todays example we will see One way and Two way data binding with Ng Model

In this Example we will use color to demonstrate how one way and two binding can be achieved with ng-Model

  1. Create your AngularJs Application

Please follow steps mentioned in below post

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

2. Create Child Component

ng generate component twowaybindingwithngmodel

3. Edit twowaybindingwith-ngmodel.component.ts

In this component we have declared variables to demonstrate one way and two way binding initially both will have red color

When user will click button it will log color and we will see if it reflects in console as per change.

twowaybindingwith-ngmodel.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-twowaybindingwith-ngmodel',
  templateUrl: './twowaybindingwith-ngmodel.component.html',
  styleUrls: ['./twowaybindingwith-ngmodel.component.css']
})
export class TwowaybindingwithNGModelComponent implements OnInit {

  twowaycolor = 'red';
  onewaycolor = 'yellow';
  constructor() { }

  ngOnInit() {
  }

  click() {
    console.log('Two way color:' + this.twowaycolor);
  }

  clickme() {
    console.log('One way color:' + this.onewaycolor);
  }
}



4. Edit HTML File twowaybindingwith-ngmodel.component.html

Here we are adding button which will be get clicked to print color on console.

IN first block we have used two way binding with

Enter Color  : <input [(ngModel)] ='twowaycolor'> 

And in second blod we are using it for one way data binding

 Enter Color  : <input [ngModel] ='onewaycolor'> 

When in first block twowaycolor value get changed and will click button it will be get printed because data will be get passed from component to view and view to Component in bi-direction.

When in second block onewaycolor value get changed and will click button it will be print old value because new value from view is not getting passed to component as its using unidirectional data binding with [ngModel

twowaybindingwith-ngmodel.component.html

<p>One and Two way Binding with NG Model</p>
<div class="card-panel   blue ">
    <h2>Two way Binding</h2>
    Enter Color : <input [(ngModel)]='twowaycolor'>
    <br>
    Color value is: {{twowaycolor}}

    <br>
    <button (click)="click()"> CLickme</button>


</div>
<div class="card-panel   blue lighten-3">
    <h2>One way Binding</h2>
    Enter Color : <input [ngModel]='onewaycolor'>
    <br>
    Color value is: {{onewaycolor}}

    <br>
    <button (click)="clickme()"> CLickme</button>
</div>






Ng Model need to declare form module in app.module.ts else it will give you error .Kindly add FormsModule in app.module.ts so kindly add like below code base

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TwowaybindingwithNGModelComponent } from './twowaybindingwith-ngmodel/twowaybindingwith-ngmodel.component';
import { FormsModule } from '@angular/forms';
import { NgclassandngstyleComponent } from './ngclassandngstyle/ngclassandngstyle.component';

@NgModule({
  declarations: [
    AppComponent,
    TwowaybindingwithNGModelComponent,
    NgclassandngstyleComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

5. Add Materialize css in index.html

In Index.html we will add materialize css and js file to use elegant UI

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularJSTwoWayDataBanding</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
       
</head>
<body>
  <app-root></app-root>
</body>
</html>

6. Edit app.component.ts : This is parent component

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'AngularJSInBuiltDirectives';

}



7. Edit app.component.html

We have added ngmodel component in app.component.html

app.component.html

<div class="card-panel   blue lighten-3">
    <app-twowaybindingwith-ngmodel></app-twowaybindingwith-ngmodel>
    
    </div>




8. Run Application

If you clone entire project then first run npm install so all dependencies will get downloaded.

Then run below command

ng serve --open

You will get below kind of output for your project once it get compiled and it will open your application in browser

9. Check Outpput

go to http://localhost:4200 path in browser

We need to enter new color in text box

After editing color in both input boxes. Change only reflected in first color and not in second one that says first one is having two way data binding and second one is having one way data binding.

Now we will click on button to check value in component.

Below screenshot displays One and Two way data binding between variables using ng model

This example demonstrated that v ng-Model can be used for one and two way binding.

Source Code:https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives

Angular JS One way Data Binding

One-way binding does below things:

  1. Angular js provide one way data binding when you use [] symbol with property or when you use interpolation .data is getting passed from view to component and from component to view.

In One way binding if user change anything in child component andonly one way communication is established with variable then that value wont get reflected in parent

In todays example we will see One way binding between Angularjs child and parent component.

In this Example we will pass color from parent to child while intantiation and then change color form child .

When color in child element get changed it should not be get reflected in parent component because only one way binding is establieshed

  1. Create your AngularJs Application

Please follow steps mentioned in below post

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

2. Create Child Component

ng generate component onewaybinding

3. Edit onewaybinding.component.ts

In this component we have declared one input varibale in which we will get value from parent component and we will modify that variable and same will be get passed to parent using output event.

Here we are changing color value to green when user click button.

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';

@Component({
  selector: 'app-onewaybinding',
  templateUrl: './onewaybinding.component.html',
  styleUrls: ['./onewaybinding.component.css']
})
export class OnewaybindingComponent {


  @Input()
  childcolor: string;




  change()  {
this.childcolor = 'green';

  }




}

4. Edit HTML File onewaybinding.component.html

Here we are adding button which will be get clicked to change color and change() function will get called.

We are using childcolor variable to assign to color style

<p>onewaybinding works!</p>

<h4>Child Color:{{childcolor}}</h4>

<button class="btn waves-effect waves-light"  (click)="change()">Change to Green</button>
<h1 [(style.color)]="childcolor" > Oneway Child</h1>



5. Add Materialize css in index.html

In Index.html we will add materialize css and js file to use elegant UI

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularJSTwoWayDataBanding</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
       
</head>
<body>
  <app-root></app-root>
</body>
</html>

6. Edit app.component.ts : This is parent component

In Parent we have declared variable and initial color will be red.

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  title = 'AngularJSTwoWayDataBanding';


  parentcolor = 'red';

}



7. Edit app.component.html

Whenever you will use child component you have to use child input variable which need one way binding and pass parent property for which you want one way binding. like below screenshot .

In below app.component.html we are using it for multiple examples but we will just concentrate on code base mentioned in below screen.

<div class="card-panel   blue lighten-3">
  <h3>One Way Data Binding with  Parent Child</h3>
<app-onewaybinding [childcolor]="parentcolor"></app-onewaybinding>

<h4>Parent Color:{{parentcolor}}</h4>
<h3 [style.color]="parentcolor" > Parent Component</h3>
</div>

<div class="card-panel   blue lighten-3">
  <h3>Two Way Data Binding with  Parent Child</h3>
<app-twowaypropertychange [(childcolor)]="parentcolor"></app-twowaypropertychange>

<h4>Parent Color:{{parentcolor}}</h4>
<h3 [style.color]="parentcolor" > Parent Component</h3>
</div>





8. Run Application

If you clone entire project then first run npm install so all dependencies will get downloaded.

Then run below command

ng serve --open

You will get below kind of output for your project once it get compiled and it will open your application in browser

9. Check Outpput

go to http://localhost:4200 path in browser

We have set up red color in parent and passed same in child

We need to click change to green button so we will see data change between parent and child

After clicking button you will get below output

This example demonstrated that value can be passed form parent component to child but if child modifies this value it wont be reflected in parent as its used one way data binding.

Source Code:https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSTwoWayDataBanding

Angular JS Two way Data Binding

Basics of two-way binding

Two-way binding does two things:

  1. Sets a specific element property.
  2. Listens for an element change event.

In Angular JS two way data binding is denoted by [()] its also called banana sign.

This is combination of property binding “[]” and event binding “()”

Two way binding helps user to setup communication between component to view and view to componetn so its bi directional communicaiton that will help user.

This will be useful when user changes anything in child component and that value needs to be reflected in parent component .

In Angular formmodule ngModel will provide two binding between component and view .

In todays example we will see Two way binding between Angularjs child and parent component.

In this Example we will pass color from parent to child while intantiation and then change color form child .

When color in child element get changed it should get reflected in parent component

  1. Create your AngularJs Application

Please follow steps mentioned in below post

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

2. Create Child Component

ng generate component twowaypropertychange

3. Edit twowaypropertychange.component.ts

In this component we have declared one input varibale in which we will get value from parent component and we will modify that variable and same will be get passed to parent using output event.

Kindly use below naming convention for input and output .keep same name as prefix( e.g. childcolor) and then ass suffix as Change to it.

Here when function is changing value we are emitting same value to parent variable by passing child elements input variable back.

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';


@Component({
  selector: 'app-twowaypropertychange',
  templateUrl: './twowaypropertychange.component.html',
  styleUrls: ['./twowaypropertychange.component.css']
})
export class TwowaypropertychangeComponent  {

  @Input()
  childcolor: string;

  @Output()
  childcolorChange = new EventEmitter<string>();


  change()  {
this.childcolor = 'green';
this.childcolorChange.emit(this.childcolor);
  }


}

4. Edit HTML File twowaypropertychange.component.html

Here we are adding button which will be get clicked to change color and change() function will get called.

We are using childcolor variable to assign to color style

</blockquote>
<h4>Child Color:{{childcolor}}</h4>
<br>

<button class="btn waves-effect waves-light"  (click)="change()">Change to Green</button>
<h1 [(style.color)]="childcolor" > Twoway Child</h1>



5. Add Materialize css in index.html

In Index.html we will add materialize css and js file to use elegant UI

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularJSTwoWayDataBanding</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
       
</head>
<body>
  <app-root></app-root>
</body>
</html>

6. Edit app.component.ts : This is parent component

In Parent we have declared variable and initial color will be red.

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  title = 'AngularJSTwoWayDataBanding';


  parentcolor = 'red';

}



7. Edit app.component.html

Whenever you will use child component you have to use child input variable which need two way binding in [()] and pass parent property for which you want two way binding. like below screenshot

</div>
<div class="card-panel   blue lighten-3">  <h3>Two Way Data Binding with  Parent Child</h3><app-twowaypropertychange [(childcolor)]="parentcolor"></app-twowaypropertychange>
<h4>Parent Color:{{parentcolor}}</h4><h3 [style.color]="parentcolor" > Parent Component</h3></div>

8. Run Application

If you clone entire project then first run npm install so all dependencies will get downloaded.

Then run below command

ng serve --open

You will get below kind of output for your project once it get compiled and it will open your application in browser

9. Check Outpput

go to http://localhost:4200 path in browser

We have set up red color in parent and passed same in child

We need to click change to green button so we will see data change between parent and child

After clicking button you will get below output

This example demonstrated that value can be passed form parent component to child but if child modifies this value it will be reflected in parent as its used two way data binding. Changed value will be emitted by child and same will b e get reflected in parent by angularjs. This way you can establish bidirectional communication between parent and child.

Source Code:https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSTwoWayDataBanding

HashMap

HashMap is one of the most widely used collection in java. As the name suggests, it is based on the hashing function and it is a collection of key value pairs represented by map. The collection is favorite question for an interviewer and hence it is critical to understand its functioning and its working.

As already told a HashMap is a collection of key value pairs. so unlike other collections where we store only one value, in a HashMap we store 2 values against each element of the collection. One being the key and other being a value.

So the concept itself is very simple and there is very little to understand here. The collection is unordered which means the order of retrieval is not guaranteed. These are mere basic of the map.

Lets now understand how they are stored and how the hashing function is used. So when we call put function on a map with a key and value pair, the map stores this at some part of the array and array in a map is collection of node.

The collection uses the hascode function of the object being stored to determine the index of the array within the hashmap where the object will be stored. Feels a little complicated ?

lets say we are storing employee details against employee id. So in our case, employee id is the key and employee details will be the value. Lets say we are storing “A101”,EmployeeDetail[“name:Sushil”,”email: sushil@gmail.com”]

So when we call put function with key “A101” which is String object, then the hashcode function of this object will be called to generate a number and this number will be used to determine the exact location of the pair within the map.

So why really is it done this way ? I can still store a pair in list if I create a class with key and value, isn’t it ?

The answer is to make retrieval faster. Lets see how the above mentioned storage method makes retrieval faster.

So at the time of retrieval, I present the collection with the key. In our case is “A101”, In order to determine the position of the value object, hashmap will again use the hashcode function to find our where it has stored the value of the key. So the hashcode function will help determine the index within the map and it can directly go that location to find out the value as it would be the same position which will be used for storing the pair initially.

So seems ok at this moment. So we have one key and one value and we can find the location within the map for our object and get the value. So it will be faster than traversing the list and then each time trying to find if the key in the list is equal to the key presented. So HashMap will be much faster in retrieval when we are looking for a specific object in the collection.

hashcode’s are not supposed to be unique, two objects can have the same hashcode and its logically permissible. We are supposed to make them as unique as possible but it may not be possible all the time.

So what happens when we have 2 objects with same hascode ? How will the HashMap manage the storing and retrieval. Lets see.

So during storage as earlier stated it will used the hashcode function to determine the index within the map and then against that index store the pair in a list, In this case its a linked list. For illustration look at the below example

So the bucket is really the linked list which stores the elements in a list having the same hashcode. So against each index there is a linked list where the key value pairs are stored.

So if there are more than one element with the same hascode then the element is stored in the linked list.

At the time of retrieval, the hashmap will first identify the index and then traverse through the linked list to find the element matching the key using the equals method in the object.

So the equals and hascode methods are very important when storing values in the Map. Java has provided the hashcode and equals methods for the wrapper classes but if you wish to use user defined objects as key in the HashMap then you must override the equals and hashcode methods for the HashMap to work correctly.

2 different objects can have the same hashcode. If the hashcode is same, then it does not mean that both the objects are equal. However if 2 objects are equal, they must evaluate to same hashcode. This is primary rule you must keep in mind while overriding these two methods.

You must also note that you must try and create unique hashcode for each object as it would help in the performance of the map. A hashcode which returns the same integer all the time is also a correct implementation but then it will affect the performance of the HashMap as all the elements will be stored in the same bucket.

When we try and store two objects which are logically not equal but evaluate to same hascode, a hash collision is said to be occurred. This scenario must be avoided to improve the performance of the HashMap.

If you find this tutorial helpful, Please like it and comment if you are looking of any additional information on HashMaps.

Django + Postgres

Until now we have used the SQLite database for all of our tutorials. Lets see how to configure a different database in our django projects.

Pre-requisite – Postgres database installed on your machine.

Git reference project – https://github.com/letsblogcontent/Python/tree/master/django_postgres

Step 1 – If not already installed, install django

pip install django

Step 2 – Create a new django project “django-postgres”

django-admin startproject django-postgres

Step 3 – Navigate to project directory “django-postgres” to Install django restframework

cd django-postgres
pip install djangorestframework


Step 4 – Install psycopg2 – Adapter for postgres

pip install psycopg2

Step 5 – now lets create a new app

python manage.py startapp models


Step 6 – Add the app to the installed apps of your project in the file settings.py. You will find it under “<root directory>/django-postgres”

'models.apps.ModelsConfig'
settings.py

Step 7 – Update the databases section in the settings.py file of the project to have postgres database details. Name represents database name and other parameters are self explanatory. Update all the details.


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'Test2',
        'USER': 'user1',
        'PASSWORD': 'user1',
        'HOST': 'localhost',
        'PORT': '',
    }
}

Step 8 – Lets create a model in the models app so that we can test the database configuration. In the models app directory update below files. Create files where they are not already present.

<root_dir>/django_postgres/models/models.py

from django.db import models


class Company(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=100)
    email = models.CharField(max_length=50)

Here we have create a simple model class named Company

Create a new file serializers.py file in the models app
<root_dir>/django_postgres/models/serializers.py

from rest_framework import serializers
from .models import  Company


class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ['id', 'name', 'address', 'email']

in the views.py file of models app, add following content. Here we are using viewsets to configure our views for company

<root_dir>/django_postgres/models/views.py


from rest_framework import generics, viewsets
from .models import Company
from .serializers import CompanySerializer


class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer

Create/Update urls.py file to create url mapping of company views

<root_dir>/django_postgres/models/urls.py

from django.urls import path, include
from . import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('company', views.CompanyViewSet)

urlpatterns = [
    path('', include(router.urls))
]

update the urls.py file of the project django_postgres. Add a new entry as below in the urlpatterns section

 path('api/', include('models.urls')),



Step 9 – We are pretty much done and now is the time to test our project. I have updated the project in the git url mentioned at the start of the page. If something is not working, please do write in comments or try and download the project and execute.

Execute “makemigrations” and “migrate” command as below

python manage.py makemigrations
python manage.py migrate


Now run the server with below command

python manage.py runserver


Step 10 – Now on your browser execute http://localhost:8000/api/company

Now try and add some new elements and see the results. You can also go to postgres database and you should find models_company table created with the entries you have created.

AngularJS Routing with Parameter

AngularJs provides inbuilt routing framework,This will take 10 min to setup routing for any project in Angularjs

In todays post we will see how to configure routing for Angular Js application

There are two ways to add rouiting in angularjs

1.While creating application angular will ask if routing is required or not.like below screen shot

2. Write your own typescript file and exports routing

Today we will be going to see first approach by creating routing while creating application in angularjs.

This will create below files along with your project

app-routing.module.ts

Entry for this will be added in app.module.ts file

  1. Create your angular Application

Setup Angular JS Application

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

while creating angular application kindly select routing yes

2. Add Two components in your applications

ng generate component firstpage

ng generate component secondpage

This will look like below screenshot

3. Now Add routing in typescript class and add routing for these components

4. Add <router-outlet></router-outlet> tag and anchor tags for your routing in app.component.html page

we have created 3 routs here

      
          <nav>
            <div class="nav-wrapper">
              <a href="#" class="brand-logo">Logo</a>
              <ul id="nav-mobile" class="right hide-on-med-and-down">
                <li><a [routerLink]="['/']">Home</a></li>
                <li><a  [routerLink]="['/first']">First Page</a></li>
                <li><a [routerLink]="['/second/3']">Second Page</a></li>
              </ul>
            </div>
          </nav>

<router-outlet></router-outlet>

5. Edit secondpage comonent

secondpage.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-secondpage',
  templateUrl: './secondpage.component.html',
  styleUrls: ['./secondpage.component.css']
})
export class SecondpageComponent implements OnInit {
  private sub:any;
  constructor(private route: ActivatedRoute) { }
  id = 0;

  ngOnInit() {
    // Subscribe to route params
    this.sub = this.route.params.subscribe(params => {

      this.id = params['id'];

      console.log(this.id);
  });
}

}




secondpage.component.html

<p>secondpage works! </p>
<p>in route parameter is {{id}}</p>

6. Run your application and test your routings

If you clone entire project then first run npm install so all dependencies will get downloaded.

Then run below command

ng serve --open

You will get below kind of output for your project once it get compiled and it will open your application in browser

7. Test Routes ,now click on first page and second page link from menu

When you clicked on second link it has taken input parameter and displayed on page

Now if you see both hyperlinks are working as routers for us ..This way your create centralized routing mapping in angularjs and use in your applicaiton

Source Code: https://github.com/letsblogcontent/AngularJS/tree/master/routingwithparameter

View Session information

Lets see how to view session information in django

From our previous tutorial, we now know how to setup authentication. We know how to create an admin user or a normal user. here is the git link if you have not gone through the tutorial already. https://letsblogcontent.wordpress.com/2020/09/18/django-authentication/

We are going to build on from the previous tutorial – https://letsblogcontent.wordpress.com/2020/09/18/django-authentication/

You can start directly from this tutorial, just copy the contents from the git repo “pip install -r requirements.txt”

Step 1 – We will now create an app to view session information. lets call this app “admin-data-viewer”. Execute below command

python manage.py startapp AdminModels

Register the app into the project under the INSTALLED_APPS object

Step 2 – This will create a new app with admin.py inside the app.

from django.contrib import admin
from django.contrib.sessions.models import Session


class SessionAdmin(admin.ModelAdmin):
    def _session_data(self, obj):
        return obj.get_decoded()
    list_display = ['session_key', '_session_data', 'expire_date']

admin.site.register(Session,SessionAdmin)

Step 3 – If you have not created a user, lets create a super user. Execute below command and follow instructions

python manage.py createsuperuser

Step 4 – execute makemigrations and migrate

python manage.py makemigrations
python manage.py migrate

Step 5 – Run the server

python manage.py runserver

Step 6 – Navigate to http://127.0.0.1:8000/admin&#8221; and provide the admin username and password created in step 3 and look for b

Click on sessions to see below information about session

AngularJS Routing Example

AngularJs provides inbuilt routing framework,This will take 10 min to setup routing for any project in Angularjs

In todays post we will see how to configure routing for Angular Js application

There are two ways to add rouiting in angularjs

1.While creating application angular will ask if routing is required or not.like below screen shot

2. Write your own typescript file and exports routing

Today we will be going to see second approach by creating class

  1. Create your angular Application

Setup Angular JS Application

Hello World with Angular JS

Prerequisites Angularj JS new version is using nodejs for setting up application and for running applicaion you will also need any code editor tool. For current setup we are using visual code studio Kindly down load latest version of nodejs and visual code studio on your machine and complete setup Node Installation 1 Go to…

2. Add Two components in your applications

ng generate component firstpage

ng generate component secondpage

This will look like below screenshot

3. Now Add routing typescript class and add routing for these components

4. Import this exported routing in app.module.ts file

5. Add <router-outlet></router-outlet> tag and anchor tags for your routing in app.component.html page

Refer Router link for more details:https://angular.io/api/router/RouterLink

6. Run your application and test your routings

7. Test Routes ,now click on first page and second page link from menu

Now if you see both hyperlinks are working as routers for us ..This way your create centralized routing mapping in angularjs and use in your applicaiton

Source Code: https://github.com/letsblogcontent/AngularJS/tree/master/routingexample