Design a site like this with WordPress.com
Get started

Python – Variable

In python variable get declared when you assign value to variable first time

x=10;  #x will be integer
y='abcd' #y will be string
print(x)
print(y)

This will declare x as integer and y as string and you can also check data types as coded in below sample.

Find Type of Variable

you can use “type” keyword to find type of variable

Below is sample code and output

In Python variable names are case sensitive

x=10;  #x will be integer
y='abcd' #y will be string
X= 'Ten'

print( 'Value of small x=' ,x)
print('Value  of y=',y)
print('Value  of X=', X)

print( 'Type of small x=' ,type(x))
print('Type of y=',type(y))
print('Type of X=', type(X))

Output of this code will be as below

Value of small x= 10
 Value  of y= abcd
 Value  of X= Ten 
 Type of small x= <class 'int'>
 Type of y= <class 'str'>
 Type of X= <class 'str'>




Angular JS Data inbuilt Directives NgStyle and NgClass

In this Example we see inbuilt angularjs Directives

  1. NgStyle
  2. NgClass

NgClass and NgStyle

Lets go through basics first

NgClass


This directive is used when you want to select class of element on certain conditions

The syntax is: 

<h3 [ngClass]="{'myclass': flag}"> Change Class</h3>

NgStyle


This directive is getting used to apply multiple styles at a same time as array from variable or it can be also used to change style base on conditions

The syntax is:   

 <h3 [ngStyle]="{'color': flag  ? 'red':'green' }">Change Style</h3>

  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 … Continue reading “Hello World with Angular JS”

Create Components

In this example we have created multiple component which can be refereed in git repo

https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives/src/app

Use below command to generate these components

ng generate component <componentname>

For demonstrating this we have created below component in git project

ng generate component NgclassandngstyleComponent

Please refer:

https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives/src/app/ngclassandngstyle

Lets look at code of this one

ngclassandngstyle.component.ts

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

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

  constructor() { }
  flag = false;

  ngOnInit() {
  }

  changeClass() {
    this.flag = true;
  }

}


We have declared variable which is boolean and initial value is false and it will get changed when use clicks on button from UI and flag will become true

ngclassandngstyle.component.html

<p>ngclassandngstyle works!</p>

<h3 [ngClass]="{'blue-text text-darken-2': flag}"> Change Class</h3>
<h3 [ngStyle]="{'color': flag  ? 'red':'green' }">Change Style</h3>
<button (click) ="changeClass()"> Change Class</button>

In this code we are dynamically applying class and style to h1 element base on “flag” declared in component above. Initially its false so no class will be applied but style color will be green for false value.

Once use click button and “changeClass()” function will called value of flag will be true and class will get applied as “blue-text text-darken-2′” and style color will be red.

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 { }

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>

We have added js file and css file specific to materilize css

https://materializecss.com/

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';

}



Edit app.component.html

We have added ngmodel component in app.component.html

We have added all components mentioned above in tutorial .You can remove or add as per you need.

app.component.html

<app-ng-if-ng-for-ng-switch></app-ng-if-ng-for-ng-switch>

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

    </div>

</div>




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

Check Outpput

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

In main html we have imbedded all three components.

Lets see output of this

Now click button and check for class and style

After clicking on button it changes style and color of text

We have combined all above mentioned examples on single page in app.component.html and it will look like below on browser so you can play with all 3 components

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

Angular JS NgIf and NgFor and NgSwitch

In this Example we will see inbuilt angularjs Directives

  1. NgIf
  2. NgFor
  3. NgSwitch

NgIf ,NgFor and NgSwitch

Lets go through basics first

NgIf


This directive is used when you want to display or remove an element based on a condition.

The syntax is: 

*ngIf=”<condition>”

NgFor


This directive is getting used to iterate through collection

The syntax is:    

<ul *ngFor =" let n of newcars">

NgSwitch


NgSwitch is like the JavaScript switch statement. It displays one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM.

NgSwitch is actually a set of three, cooperating directives: NgSwitchNgSwitchCase, and NgSwitchDefault as in the following example.

The syntax is:    

<ul *ngFor=" let c of newcars" [ngSwitch]="c.name">

            <li *ngSwitchCase="'city'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>
            <li *ngSwitchCase="'polo'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>

            <li *ngSwitchDefault class="text-success">{{ c.name }} {{ c.average }}
            </li>

        </ul>

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 … Continue reading “Hello World with Angular JS”

Create Components

In this example we have created multiple component which can be refereed in git repo

https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives/src/app

Use below command to generate these components

ng generate component <componentname>

For demonstrating this we have created below component in git project

ng generate component NgIfNgForNgSwitchComponent

Please refer:


https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives/src/app/ng-if-ng-for-ng-switch

Lets look at code of this one

ng-if-ng-for-ng-switch.component.html

<p>ng-if-ng-for-ng-switch works!</p>

<div class="row">

    <div class="col s3" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>{{title}}</h4>

        <ul *ngFor=" let c of cars">

            <li> {{c}}</li>


        </ul>
    </div>
    <div class="col s3" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>Display data with ngFor and ngIf</h4>

        <ul *ngFor=" let n of newcars">

            <li style="color:red" *ngIf="n.average < 7 "> {{n.name}}</li>

        </ul>

    </div>

    <div class="col s4" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>Display data with Switch Directive</h4>
        <ul *ngFor=" let c of newcars" [ngSwitch]="c.name">

            <li *ngSwitchCase="'city'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>
            <li *ngSwitchCase="'polo'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>

            <li *ngSwitchDefault class="text-success">{{ c.name }} {{ c.average }}
            </li>

        </ul>
    </div>






</div>

In this code we are first printing all car names using for loop

In second for loop we are filtering cars whose average is less than 7.

In third block we are using switch case so we can apply different class to different cars based on name comparison

ng-if-ng-for-ng-switch.component.ts

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

@Component({
  selector: 'app-ng-if-ng-for-ng-switch',
  templateUrl: './ng-if-ng-for-ng-switch.component.html',
  styleUrls: ['./ng-if-ng-for-ng-switch.component.css']
})
export class NgIfNgForNgSwitchComponent implements OnInit {

  constructor() { }

  title = 'Display Cars';
  cars = ['city', 'nexon' , 'vento'];

  newcars = [
new Car('city', 10),
new Car('polo', 5),
new Car('vento', 6),
  ];

  ngOnInit() {
  }

}

In this component we are populating array of cars.

car.ts

export class Car {
    name: string;
    average: number;

    constructor( name , average) {
        this.name = name;
        this.average = average;
    }

}

In Above code we have declared car as class and with if we are filtering out some of cars based on use of different combination of ngIf,ngfor and ngswitch directives

After running this it will show below output

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 { }

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>

We have added js file and css file specific to materilize css

https://materializecss.com/

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';

}



Edit app.component.html

We have added ngmodel component in app.component.html

We have added all components mentioned above in tutorial .You can remove or add as per you need.

app.component.html

<app-ng-if-ng-for-ng-switch></app-ng-if-ng-for-ng-switch>

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

    </div>

</div>




In main html we have imbedded all three components.

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

This example demonstrated that ngIF and NgFor working fine

We have combined all above mentioned examples on single page in in git repo in app.component.html and it will look like below on browser so you can play with all 3 components

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

Angular JS Data inbuilt Directives

In this Example we see inbuilt angularjs Directives

  1. NgIf
  2. NgFor
  3. NgSwitch
  4. NgModel
  5. NgStyle
  6. NgClass

  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 … Continue reading “Hello World with Angular JS”

2. Create Components

In this example we have created multiple component which can be refereed in git repo

https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives/src/app

Use below command to generate these components

ng generate component <componentname>

NgIf ,NgFor and NgSwitch

Lets go through basics first

NgIf


This directive is used when you want to display or remove an element based on a condition.

The syntax is: 

*ngIf=”<condition>”

NgFor


This directive is getting used to iterate through collection

The syntax is:    

<ul *ngFor =" let n of newcars">

NgSwitch


NgSwitch is like the JavaScript switch statement. It displays one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM.

NgSwitch is actually a set of three, cooperating directives: NgSwitchNgSwitchCase, and NgSwitchDefault as in the following example.

The syntax is:    

<ul *ngFor=" let c of newcars" [ngSwitch]="c.name">

            <li *ngSwitchCase="'city'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>
            <li *ngSwitchCase="'polo'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>

            <li *ngSwitchDefault class="text-success">{{ c.name }} {{ c.average }}
            </li>

        </ul>

For demonstrating this we have created below component in git project

ng generate component NgIfNgForNgSwitchComponent

Please refer:


https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives/src/app/ng-if-ng-for-ng-switch

Lets look at code of this one

ng-if-ng-for-ng-switch.component.html

<p>ng-if-ng-for-ng-switch works!</p>

<div class="row">

    <div class="col s3" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>{{title}}</h4>

        <ul *ngFor=" let c of cars">

            <li> {{c}}</li>


        </ul>
    </div>
    <div class="col s3" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>Display data with ngFor and ngIf</h4>

        <ul *ngFor=" let n of newcars">

            <li style="color:red" *ngIf="n.average < 7 "> {{n.name}}</li>

        </ul>

    </div>

    <div class="col s4" style="border: brown; border-style: dashed; margin: 10px;">
        <h4>Display data with Switch Directive</h4>
        <ul *ngFor=" let c of newcars" [ngSwitch]="c.name">

            <li *ngSwitchCase="'city'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>
            <li *ngSwitchCase="'polo'" class="blue-text text-darken-2">{{ c.name }} {{ c.average }}
            </li>

            <li *ngSwitchDefault class="text-success">{{ c.name }} {{ c.average }}
            </li>

        </ul>
    </div>






</div>

In this code we are first printing all car names using for loop

IN second for loop we are filtering cars whose average is less than 7.

In third block we are using switch case so we can apply different class to different cars based on name comparison

ng-if-ng-for-ng-switch.component.ts

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

@Component({
  selector: 'app-ng-if-ng-for-ng-switch',
  templateUrl: './ng-if-ng-for-ng-switch.component.html',
  styleUrls: ['./ng-if-ng-for-ng-switch.component.css']
})
export class NgIfNgForNgSwitchComponent implements OnInit {

  constructor() { }

  title = 'Display Cars';
  cars = ['city', 'nexon' , 'vento'];

  newcars = [
new Car('city', 10),
new Car('polo', 5),
new Car('vento', 6),
  ];

  ngOnInit() {
  }

}

In this component we are populating array of cars.

car.ts

export class Car {
    name: string;
    average: number;

    constructor( name , average) {
        this.name = name;
        this.average = average;
    }

}

In Above code we have declared car as class and with if we are filtering out some of cars based on use of different combination of ngIf,ngfor and ngswitch directives

After running this it will show below output

NgClass and NgStyle

Lets go through basics first

NgClass


This directive is used when you want to select class of element on certain conditions

The syntax is: 

<h3 [ngClass]="{'myclass': flag}"> Change Class</h3>

NgStyle


This directive is getting used to apply multiple styles at a same time as array from variable or it can be also used to change style base on conditions

The syntax is:   

 <h3 [ngStyle]="{'color': flag  ? 'red':'green' }">Change Style</h3>

For demonstrating this we have created below component in git project

ng generate component NgclassandngstyleComponent

Please refer:

https://github.com/letsblogcontent/AngularJS/tree/master/AngularJSInBuiltDirectives/src/app/ngclassandngstyle

Lets look at code of this one

ngclassandngstyle.component.ts

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

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

  constructor() { }
  flag = false;

  ngOnInit() {
  }

  changeClass() {
    this.flag = true;
  }

}


We have declared variable which is boolean and initial value is false and it will get changed when use clicks on button from UI and flag will become true

ngclassandngstyle.component.html

<p>ngclassandngstyle works!</p>

<h3 [ngClass]="{'blue-text text-darken-2': flag}"> Change Class</h3>
<h3 [ngStyle]="{'color': flag  ? 'red':'green' }">Change Style</h3>
<button (click) ="changeClass()"> Change Class</button>

In this code we are dynamically applying class and style to h1 element base on “flag” declared in component above. Initially its false so no class will be applied but style color will be green for false value.

Once use click button and “changeClass()” function will called value of flag will be true and class will get applied as “blue-text text-darken-2′” and style color will be red.

Lets see output of this

Now click button and check for class and style

You can see NgClass and NgStyle are working as expected

NgModel

  1. NgModel Overview

This directive allows you to display a data property and update that property when the user makes changes. You have to use FormModule and need to import in your module to use this.

This supports two way data binding in forms

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>

We have added js file and css file specific to materilize css

https://materializecss.com/

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

We have added all components mentioned above in tutorial .You can remove or add as per you need.

app.component.html

<app-ng-if-ng-for-ng-switch></app-ng-if-ng-for-ng-switch>

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

    </div>

</div>




In main html we have imbedded all three components.

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 ng-Model can be used for one and two way binding.

We have combined all above mentioned examples on single page in app.component.html and it will look like below on browser so you can play with all 3 components

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

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 … Continue reading “Hello World with Angular JS”

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 … Continue reading “Hello World with Angular JS”

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 … Continue reading “Hello World with Angular JS”

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 … Continue reading “Hello World with Angular JS”

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 … Continue reading “Hello World with Angular JS”

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