-4

I have two component in my angular 4 application and i want to share values between them.

the first component has a dropdown button which ,when selecting an item,allows me to send data to another component to print it.

i wrote this code the service

    import { Injectable } from '@angular/core';


@Injectable()
export class DataService {
    private message : String ;

    sendMessage(message: string) {
        this.message=message;
    }

    getMessage(): String {
        return this.message;
    }
}

the component wich has the dropdown button

export class ToolbarDropdownComponent implements OnInit {

  message: any ;


  constructor(private loginservice:LoginService,private dataService: DataService) { }

  ngOnInit() {
  sendMessage(): void {
this.dataService.sendMessage(this.message);
}

}

the other component

 constructor(
           private dataservice: DataService
  ) { }

  ngOnInit() {    


console.log("emitted message is"+this.dataservice.getMessage());



  }
Wassim Makni
  • 471
  • 2
  • 9
  • 21

2 Answers2

0

If your components have no connection to each other (child parent etc.) I would recommend using service for that. However, I assume your components are related and in that case you can use Inputs and Outputs to do that.

If your components are both children of the same parent you can output the value to the parent and then input to the second child.

izulito
  • 477
  • 3
  • 12
-1

you can use an attribute of the first component as input for the seconde component so you can watch it in the second component and update your interface.

I hope this helped you.