Monday, July 16, 2018

Communication between Components

Communication between components

in angular, we can provide the communication between components.
in angular, we can provide communication between components in 4 ways.

1) @Input
2) @Output
3) @ViewChild
4) @ViewChildren


1) @Input :--  this decorator used to provide the
communication between parent to child component.

Steps
--------
1) Crate the angular application
       > ng new InputOutputDemo

2) Create the child component with @Input decorator
       > ng g c components/child

 3) Create the parent component with "Products array"
       >ng g c components/parent


child.components.ts

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

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

  // @Input() p_id;
  // @Input() p_name;
  // @Input() p_cost;

  @Input('_id') p_id;
  @Input('_name') p_name;
  @Input('_cost') p_cost;

  constructor() { }

  ngOnInit() {
  }

public clickMe(){
  alert(this.p_id+"---"+this.p_name+"---"+this.p_cost)
}

}




child.components.html

<h2>Product ID: {{p_id}}</h2>
<h2>Product Name: {{p_name}}</h2>
<h2>Product Cost: {{p_cost}}</h2>

<button (click)="clickMe()">Click Me</button>

<hr>



parent.components.ts

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

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

private products:Array<any>;

constructor() {

this.products=[
{p_id:111, p_name:"p-One", p_cost:10000},
{p_id:222, p_name:"p-Two", p_cost:20000},
{p_id:333, p_name:"p-Three", p_cost:30000},
{p_id:444, p_name:"p-Four", p_cost:40000},
{p_id:555, p_name:"p-Five", p_cost:50000}
]

}

ngOnInit() {
}

}


parent.components.html


<!-- <app-child
[p_id]="x.p_id"
[p_name]="x.p_name"
[p_cost]="x.p_cost"
*ngFor="let x of products">

</app-child> -->

<app-child
[_id]="x.p_id"
[_name]="x.p_name"
[_cost]="x.p_cost"
*ngFor="let x of products">

</app-child>


app.module.ts

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

import { AppComponent } from './app.component';
import { ChildComponent } from './components/child/child.component';
import { ParentComponent } from './components/parent/parent.component';

@NgModule({
declarations: [
AppComponent,
ChildComponent,
ParentComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [ParentComponent]
})
export class AppModule { }


index.html

<body>
<app-parent></app-parent>
</body>


OUTPUT


No comments:

Post a Comment