Setting or passing a variable via URL in Angular 2 applications

I am working on an Angular2 application that includes a chart component. Users can adjust the chart by setting certain variables. I want to give users the option to have the chart preset with specific variables by using a URL link.

For instance:

localhost:4200/app/chart?height=500;width=400;color=blue

Within the component, there are variables named:

this.height: number;
this.width: number;
this.color: string;

My main inquiry is how can I set these variables from the URL link when the component loads (on init)?

Secondly, how can I pass these variables into the URL itself? If I have the following variables:

this.height: number = 500;
this.width: number = 400;
this.color: string = blue;

How do I include them in the URL like this:

localhost:4200/app/chart?height=500;width=400;color=blue`

This is my routing configuration:

import { Routes, RouterModule } from '@angular/router';

import { ChartComponent } from './chart/chart/index';

const appRoutes: Routes = [
  { path: 'app', component: AppComponent,
    children: [
      { path: 'chart', component: ChartComponent },
      { path: '', component: DashboardComponent }
    ]},

  // Redirect all other routes to home
  { path: '**', redirectTo: '' }
 ];

export const routing = RouterModule.forRoot(appRoutes);

Answer №1

function initializeParams(route) {
    let height = 0;
    let width = 0;
    let color = '';

    route.params.subscribe(
        (params) => {
            if(params['height']) {
                height = params['height'];
            }
            if(params['width']) {
                width = params['width'];
            }
            if(params['color']) {
                color = params['color'];
            }
        }
    );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most reliable method for converting a 32-bit unsigned integer to a big endian byte array?

Looking for a simple and reliable method to convert an unsigned integer into a four-byte-array in big endian format, with padding if necessary? Take a look at this example: Input value: 714 Output: Resulting byte array [ 0xca, 0x02, 0x00, 0x00 ]; By the ...

Exploring the world of JSON manipulation in JavaScript

I've been experimenting with JSON recently and came across something I don't quite understand. Here is an example of some code I used: var str = "{'name':'vvv'}"; var cjson = eval ("(" + str + ")"); alert( ...

What's the best way to decrypt a string in NodeJS?

In the midst of my NodeJS & MongoDB project, I've encountered a requirement to encrypt the content of articles before they are published. The catch is that the encrypted content should only be displayed if the correct key-codes are entered. For ...

The contents of the div do not display when the button is pressed except in jsfiddle

I have written a script that triggers the appearance of a div where users can adjust the time settings for a timer. The functionality works perfectly on JSFiddle, with the div displaying as intended. However, when tested on other online IDEs such as Coding ...

I must update the menu to show only one sub-menu at a time, ensuring that multiple menus cannot be displayed simultaneously

When I click on a menu option, it displays correctly, but when I click on another option, both are displayed. The goal is to only display one at a time. https://i.sstatic.net/J6vLf.png $('.sub-menu ul').hide(); $(".sub-menu a").click( ...

Warning: Potential spacing issues when dynamically adjusting Material UI Grid using Typescript

When working with Typescript, I encountered an error related to spacing values: TS2322: Type 'number' is not assignable to type 'boolean | 7 | 2 | 10 | 1 | 3 | 4 | 5 | 6 | 8 | "auto" | 9 | 11 | 12'. No lint errors found Version: typesc ...

Displaying PartialView in Bootstrap modal and transferring ID value

I am currently working on loading a PartialView inside a Bootstrap modal. I have managed to generate the URL in my code while displaying data in a datatable. The modal and everything is functioning properly, however, the partial view is not visible. I need ...

Please ensure not to include any duplicate elements in the array

function findNeighbors(color_indices) { var neighbor_face = []; var temp_indexes = []; //initializing to specified length var len_color_indices = color_indices.length; for (var i = 0; i < len_color_indices; i++) { if (c ...

Managing Angular subscriptions to prevent memory leaks when making API requests

When I first delved into Angular, a colleague suggested using take(1) for API calls with observables in RxJs, claiming it automatically unsubscribes after one call. Believing this, I continued to use it until noticing significant rendering delays when nav ...

Utilizing Angular and ASP .Net Web Api in conjunction with Plesk hosting platform

I have successfully created a website using Angular and .NET Framework 5.0. I was able to publish the Angular portion on Plesk and it is working correctly, but I am facing challenges in publishing the .NET Framework app and connecting it with Angular. ...

Is it possible to incorporate a nested form in Angular reactive forms without utilizing an array?

this.parentForm = this._fb.group({ testControl1: [], testControl2: [], testChildForm1: this._fb.group({ testChildControl1: [], testChildControl2: [] }) )}; The parent form in the code above has two form controls and on ...

Exploring the capabilities of Angular2 in conjunction with Symfony3's FOSOAuthServerBundle for secure

Trying to integrate my angular2 frontend app with a symfony backend. Currently using FOSOAuthServerBundle (https://github.com/FriendsOfSymfony/FOSOAuthServerBundle) for authorization, but struggling to fully grasp the implementation process. Experiment ...

Is it feasible to immediately generate the result of PHP's get_class function?

Hello there, I was wondering if it's possible to output everything in one line instead of creating a variable to store it in first. Here is an example of my current code: <?php $className = get_class(); $className::CheckCreated(); ?> ...

Executing Backbone.history.start() prevents the back button from navigating away from the current page

I've encountered this issue in multiple apps, leading me to question if there's an error in my handling of Backbone history. The scenario is as follows... There are two pages: index.html app.html The index page is a standard HTML page with a l ...

The Rxjs `of` operator fails to emit a value when utilizing proxies

I ran into an issue with a basic unit test that utilizes Substitute.js (I also tried using TypeMoq mocks, but encountered the same behavior). My test simply tries to use the of operator to emit the mocked object. Surprisingly, without any additional opera ...

Is there a way for me to plot my single-element dictionary onto a map?

I am currently working on a project using reactJS and I am facing an issue with displaying information from my dictionary. Initially, I attempted to use a "for" loop to display the information, but unfortunately, it did not work as expected. Subsequently, ...

"Encountered an error while trying to access properties that

Struggling to create a practice menu with the functionality of making elements appear and disappear on click? If you are encountering issues with a class named "option" not working as expected, you are not alone. Clicking on nested objects like images or i ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...

A Kendo editor necessitates the use of Kendo JavaScript specifically designed for Angular

Can someone provide guidance on the necessary Kendo libraries for implementing the Kendo editor in AngularJS? The tutorial site suggests that "kendo.all.min.js" is required, but I am hesitant to use it due to its resource-heavy nature. Any assistance wou ...

Sending an array of complex data to a controller method in ASP.net MVC

Currently, I am in the process of migrating an ASP.net Web Forms application to MVC. This application makes use of AJAX through an Ajax-enabled WCF Web service and asp:ScriptManager. I have been sending an array of objects to the service, and it has been ...