Search code examples
angulartypescriptangular2-routingangular2-routerrouteparams

How to pass input value to different route using angular2?


So I have two components, HomePageComponent and StudentsViewComponent. In HomePageComponent I have a input tag:

<input type="text" #careerObj class="modules" placeholder="Career Objective ( software engineer)">
<button class="submit" routerLinkActive="active" [routerLink]="['/students', careerObj.value  ]">Search</button>

and I want to pass the value of this input to studentsViewComponent using params.

It redirects to the correct route, but the param is empty. The value is always empty, and Im not sure why.

Here is my route:

  {
    path: 'students/:searchQuery',
    component: StudentsViewComponent
  },

ngOnInit() {
  this.activatedRoute.params.subscribe((params: Params) => {
    console.log(params);
  });
}

not sure why the param is empty.

Please help


Solution

  • First of all the routerlink directive have issues with button types as I saw lastly on github second thing you are using element reference to pass value to router link directive use the official model binding way routerlink probably one of them is causing issue. Try this,

     <input type="text" [(ngModel)]="route" class="modules" placeholder="Career Objective ( software engineer)">
     <button class="submit" routerLinkActive="active" [routerLink]="['/students', route]">Search</button>
    

    Or

     <input type="text" [(ngModel)]="route" class="modules" placeholder="Career Objective ( software engineer)">
     <button class="submit" (click)="navigate()">Search</button>
    

    and use this function is component

    navigate(){
     this.router.navigate(["students", this.route]);
    }
    

    dont forget to inject router