Thursday 13 January 2022

 @Input(): When data is transferred from parent component to child component  

                    then Input decorator can be used.

@Output(): When data is transferred from child to parent then Output decorator 

                        can be used.





CustomerDetails.component.ts: 

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


@Component({

  selector: 'app-customer-details',

  templateUrl: './customer-details.component.html',

  styleUrls: ['./customer-details.component.css']

})

export class CustomerDetailsComponent implements OnInit {

  @Input() customer: any;

  @Output() customerChanged = new EventEmitter<any>();

  constructor() { }

 ngOnInit() {

    this.customer.name = 'Gina Doe';

    this.customer.address.city = 'Mumbai';

    

    setTimeout(() => {

      this.customer.name = 'Tina Doe';

    }, 1000);

  }

  change() {

  //  this.customer.name = 'Michelle Doe';

    this.customerChanged.emit(this.customer);

  }

}

CustomerDetails.component.html: 

Name: {{ customer.name }}
<br />
City: {{ customer.address.city }}
<br />
<button (click)="change()">Change Customer</button>

Customer.component.ts:
 
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
  customerDetails: any;
  constructor() { }

  ngOnInit() {
    // called service/store

    this.customerDetails = {
      name: 'James Doe',
      address: {
        city: 'Phoenix'
      }
    };
  }

changed(customer: any) {
  if(customer.name === 'Tina Doe'){
    this.customerDetails = {
      name: 'James Doe',
      address: {
        city: 'Phoenix'
      }
    };
  } else {
    this.customerDetails = {
      name: 'Pankaj',
      address: {
        city: 'Phoenix'
      }
    };
  }
 
}
}
Customer.component.html: 

<h1>Customer</h1>
<br />
<app-customer-details [customer]="customerDetails" (customerChanged)="changed($event)"></app-customer-details>


In Above example customer component is parent and customerDetails is child component 




PostedBy:pankaj_bhakre

No comments:

Post a Comment