Lets Have a fun with Technology.

BTemplates.com

Follow by Email

Tuesday, July 4, 2017

Share value from one component to another component in Angular 2.


Hello,

You can share value between components using Shared service.

Below is sample code for it.

in Share Service.



export class SharedService {
  private name = '';

  savedata(str){
    this.name=str; 
  }

  getData:string()
  {
    return this.name;
  }
} 


In First Component.



@Component({
  template: `
    
<input #myVal type="text" />
<button (click)="send(myVal.value)>Send</button>
`, }) export class FirstComponent{ constructor(service:SharedService){ this.service=service; } send(str){ this.service.saveData(str); } }

In Second Component



export class SecondComponent   {

  constructor(service:SharedService)
  {
    this.service=service;   
    this.myName=service.getData();
  }

}

Hope this will help you.

0 comments:

Post a Comment