I have a search filter page that displays products of the search, and also displays the product details in a modal when the user clicks on a product of the search.
I want to now set the existing id optional param of the activatedRoute programmatically when the user clicks on a product. This is why it is optional - upon first loading, it will have no params, until the user clicks it - then they can share that link to the specific product after clicking it by copy and pasting it from the browser url.
This is my attempt to programmatically set the optional param:
routes:
export const routerConfig: Routes = [
{
component: LandingPageComponent,
path: "",
},
{
component: FindPageComponent,
path: "find/:id",
},
{
component: FindPageComponent,
path: "find",
},...
set activatedRoute id optional param:
export class ResultCardComponent {
@Input() public result: Result;
@Output() public onResultClicked: EventEmitter<Result> = new EventEmitter<Result>();
public paramsSub: any;
public selectedId: any;
private resultId: string;
constructor(
private route: ActivatedRoute,
private router: Router,
) { }
public emitResult() {
this.onResultClicked.emit(this.result);
this.paramsSub = this.route.params.subscribe((params) => this.selectedId = params["id"]);
this.router.navigate(["find", this.result.id]);//only doing this as a hack workaround.
}
}
Ideally I want to remove the bottom line as to stop physically navigating which is a waste of resources
EDIT: this seems to work:
public emitResult() {
//this.onResultClicked.emit(this.result);
this.route.params['id'] = this.result.id;
}
however it doesn't change the url, i guess because it doesnt load the page again
Please see this response, for optional parameters I think you'll need to use query parameters!