Optional URL parameters in angular 6 typescript

Optional URL parameters in angular 6 typescript

My development environment details:

Angular CLI: 6.0.7
Node: 8.11.2
typescript: 2.7.2

I wanted to implement optional URL parameters in angular 6. It means, when the URL params are passed for a angular 6 route, some values in the form should be pre-populated based on the params. When the URL is not coming with any parameters, user can enter any values to the form.(not pre-populated).

There are two ways you can achieve this feature in angular 6:

1. You can define Routes with mandatory parameters
In  app-routing.module.ts

{ path: ‘getModel/:name’, component: TestModelComponent } , 

Here the name parameter has to be passed when called ‘getModel/testname’ otherwise this call will not be succeeded.

2. You can define Routes with optional parameters

Suppose, you want to populate ‘requested by’ field in the form , if the param is passed in the URL. Otherwise it will work as normal. User has to enter the value in the form field.

You don’t have to do anything in the app-routing. Where as little bit of logic change in the component.ts will suffice.

When there is requestedby=testuser in the URL:

http://localhost:4200/getModel/testmodel;requestedby=testuser 

You have to do the following steps in the app.component.ts:

1. Imports

import { ActivatedRoute, Router } from ‘@angular/router’;

2. Add constructor args

constructor(private route: ActivatedRoute, private router: Router)

3. Call the method to handle pre-population of params in ngOnInit() :

ngOnInit() {  prepopulateIfUrlParamsPassed();  }

4. Implement the prepopulateIfUrlParamsPassed() method as follows:

prepopulateIfUrlParamsPassed() {
 this.route.params.subscribe(params => {
  if(params.requestedby){
     this.requestedby = params.requestedby;
  }
 ); 
}

this.requestedby will be assigned / used in the form as model.

<input class="form-control col-sm-10" id="requestedby" name="requestedby"
[(ngModel)]="requestedby">

Now when the URL param ;requestedby=testuser is passed, the value will be automatically assigned in the form field.

Otherwise, it will be empty. User can enter any text in the form field.

Leave a Reply

Your email address will not be published. Required fields are marked *