I have some menus in the header. Now I want to add query string parameters to all header menus programmatically. My code is like this.
<nav >
<ul >
<li><a routerLink="/passenger/home" routerLinkActive="active">Home</a></li>
<li><a routerLink="/passenger/myride" routerLinkActive="active">My Ride</a></li>
<li><a routerLink="/passenger/profile" routerLinkActive="active">Profile</a></li>
</ul> </nav>
My final code will be like this:
<nav >
<ul >
<li><a routerLink="/passenger/home?pi=160016" routerLinkActive="active">Home</a></li>
<li><a routerLink="/passenger/myride?pi=160016" routerLinkActive="active">My Ride</a></li>
<li><a routerLink="/passenger/profile?pi=160016" routerLinkActive="active">Profile</a></li>
</ul> </nav>
I want to do this from ngOnInit method of a page.
ngOnInit(): void {
//add quary string to all the header menu
}
I am using Angular 13, and typescript.
I did that in a jquary project like this:
$('a[]').each(function () {
var oldUrl = $(this).attr("href");
var newUrl = oldUrl "?pi=160016";
$(this).attr("href", newUrl);
});
CodePudding user response:
You can transfer parameter from child component to parent component or you can transfer parameter from parent component to child component.
Best way is crate a service and transfer parameter by using this service.
Service code:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class QueryStringService {
constructor() { }
message: string = "";
setQueryString(data) {
this.message = data;
}
getQueryString() {
return this.message;
}
}
Child component code:
ngOnInit(): void {
this.queryStringService.setQueryString(Id);
}
Menu component code:
queryString: string = "";
constructor(
private queryStringService: QueryStringService
) { }
ngOnInit(): void {
this.queryString = this.queryStringService.getQueryString();
}
<li><a routerLink="/passenger/home" [queryParams]="{pi
:queryString }" routerLinkActive="active">Home</a></li>
<li><a routerLink="/passenger/myride" [queryParams]="{pi
:queryString }" routerLinkActive="active">My Ride</a>
</li>
<li><a routerLink="/passenger/profile" [queryParams]="{pi
:queryString }" routerLinkActive="active">Profile</a></li>
CodePudding user response:
As explained in Angular doc, you can use property binding:
HTML code:
<nav >
<ul >
<li><a [routerLink]="'/passenger/home' query" routerLinkActive="active">Home</a></li>
<li><a [routerLink]="'/passenger/myride' query" routerLinkActive="active">My Ride</a></li>
<li><a [routerLink]="'/passenger/profile' query" routerLinkActive="active">Profile</a></li>
</ul> </nav>
TS code:
query:string="";
ngOnInit(): void {
this.query="?pi=160016";
}