Search code examples
angularroutesangular7-router

send data to another component through route in angular


I am working on an angular application and realized that in the latest versions of angular, data can be transferred one component to other through routes. I have gone through some blogs but I am not very clear of how to do that.

My code

component1.ts

sendMessageto2() {
    par = this.param
    this.router.navigate(['/vav'],{state : {data : {par}}})
    console.log(this.param)
  }

I want to pass a variable this.param to component2

component1.html

<area shape="rect" coords="818,232,917,262" (click)="sendMessageto2()">

component2.ts

ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
    .pipe(map(() => window.history.state))  
  }

I am not sure how to get this data in the component2 .I get an error for map. Could not find map.Can some one help me with this?

Thanks


Solution

  • For passing data you can do this

    this.router.navigate(["/vav", { 'data': data }]);
    

    For receiving on other page

    constructor(public router: Router, public route: ActivatedRoute){}
    route.params.subscribe(params => {
            let data = params['data']
        });