Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the parameter of activated Route on button click

Basically, I have two component TodosComponent and TodoDetailsComponent. Clicking on an item in TodosComponent takes me to the TodoDetailsComponent where I grab the parameter and fetch the required data from the API. All is working great.

But I want to make a next button on my TodoDetailsComponent so that the id passed to the parameter changes and I get the desired result based on the parameter as subscribed to the activatedRoute params. I google(d) and stackoverflow(ed) a lot but unable to find an example which give me direction to carry on. Here is the working demo of the issue. Let me know if required more information. Any information will be helpful that whether is it possible or not.

TodoDetails.component.ts

@Component({
  template: `<p>Todo Details Component</p>
    <div>{{ todo | json }}</div>
    <button type="button" (click)="next()">Next</button>
  `
})

export class TodoDetailsComponent implements OnInit{
  todo;
  constructor(private activatedRoute: ActivatedRoute, private service: Service) { }

  ngOnInit() { 
    this.activatedRoute.paramMap.pipe(
      switchMap(params => this.getTodo(+params.get('id')))
    ).subscribe(todo => this.todo = todo);
  }

  getTodo(id) {
    return this.service.getTodo(id);
  }

  next() {
    // if i grab the id over here and increment 
    // by id++ the id increases but as can be seen 
    // parameter is still the same, so won't work
  }
like image 962
Suryan Avatar asked Sep 05 '25 02:09

Suryan


1 Answers

Just try to navigate to the same component by just changing the id prams

export class TodoDetailsComponent implements OnInit{
  todo;
  id: number;
  constructor(private activatedRoute: ActivatedRoute, private service: Service, 
              private router : Router) { }

  ngOnInit() { 
    this.activatedRoute.paramMap.pipe(
      switchMap(params => {
          this.id = +params.get('id')
          return this.getTodo(this.id)
      })
    ).subscribe(todo => this.todo = todo);
  }

  getTodo(id) {
    return this.service.getTodo(id);
  }

  next() {
    this.id += 1;
    this.router.navigate(['/todos',this.id]);
  } 

Hope this will work thanks - Happy coding !!

like image 64
Rahul Avatar answered Sep 07 '25 14:09

Rahul