How do I pass data to Angular routed components?

前端 未结 16 1108
挽巷
挽巷 2020-11-22 08:03

In one of my Angular 2 routes\'s templates (FirstComponent) I have a button

first.component.html

16条回答
  •  遇见更好的自我
    2020-11-22 08:23

    Pass data and route

    well the easiest way to do it in angular 6 or other versions I hope is to simply to define your path with the amount of data you want to pass

    {path: 'detailView/:id', component: DetailedViewComponent}
    

    as you can see from my routes definition, I have added the /:id to stand to the data I want to pass to the component via router navigation. Therefore your code will look like

    view
    

    in order to read the id on the component, just import ActivatedRoute like

    import { ActivatedRoute } from '@angular/router'
    

    and on the ngOnInit is where you retrieve the data

    ngOnInit() {
           this.sub = this.route.params.subscribe(params => {
            this.id = params['id'];
            });
            console.log(this.id);
          }
    

    you can read more in this article https://www.tektutorialshub.com/angular-passing-parameters-to-route/

提交回复
热议问题