Tuesday, 17 September 2019

Passing data form one component to another (Sibling component) in angular 8





This blog shows you how to pass data from one component to another using EventEmitter
First create a service that could be injected in both the component (ANGULAR CLI COMMANDng g s customer-forms’) this will create a service with the name customerForms.service.ts
Now create a method in service that will be called from component on click, Let’s call is PassData
PassData(DataSource)
    {
        console.log(DataSource);
    }

Create a EventEmitter object which will emit the data
$dataSource = new EventEmitter();

Use this $dataSource variable in PassData method
PassData(DataSource)
    {
        console.log(DataSource);
        this.$dataSource.emit(DataSource);
    }

Now let’s create a method on component which will call PassData of service
Edit(CustomerRequest)
  {
    console.log(CustomerRequest);
    this.customerRequestService.PassData(CustomerRequest);
  }

Call this method on click of any html component.
<section class="col-md-3 border cursor-action" (click)="Edit(customerRequest)" 
    *ngFor="let customerRequest of customerRequests">

After running This you will see logs in console


Now we need to handle this emit in other component
For this we need subscribe to the variable $dataSource of service in receiving component in ngInit()
this.customerRequestService.$dataSource
      .subscribe((data=> {console.log('DataSource received'data);
      this.Edit(data);
    });

And finally
  Edit(CustomerRequest)
  {
    console.log(CustomerRequest);
    this.form.setValue({
      CompanyName:CustomerRequest.CompanyName,
      Name: CustomerRequest.Name,
      SoftwareId:CustomerRequest.SoftwareId,
      RelationshipDuration:CustomerRequest.RelationshipDuration,
      RequestMessage:CustomerRequest.RequestMessage
    });
  }

After doing all this you can see that the code is working in the console of browser


Thanks
Do not forget to subcribe to my blog i.e. codeinout.blogspot.com

No comments:

Post a Comment

Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...