5

I have an application written in Angular2. In one component, there's a chart, you can adjust it by setting few variables. I would like the user to have completely set chart with these variables already set by the URL link.

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

Inside my component, there are variables called:

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

And that is my question, how can I set them exactly from the URL link, on component load? (on init)

And my second question, how can I pass these variables into URL? For example, I have these variables:

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

How can I send them to the URL? To make it look like:

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

My routing file:

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 }
    ]},

  // otherwise redirect to home
  { path: '**', redirectTo: '' }
 ];

export const routing = RouterModule.forRoot(appRoutes);
2
  • Can you please paste your route configuration? I think your answer lies in the @angular/router namespace :) Commented Mar 15, 2017 at 21:18
  • 1
    @A1rPun Done my friend Commented Mar 15, 2017 at 21:19

1 Answer 1

4
constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.params.subscribe(
      (params: any) => {
        this.height: number = params['height'];
        this.width: number = params['width'];
        this.color: string = params['color'];
      }
    );
  }
Sign up to request clarification or add additional context in comments.

7 Comments

Where to drop it? In routing file or my chart component?
In your component where you use it. And dont forget the import import {ActivatedRoute} from '@angular/router';
No this use the current URL route path
What if I want to send these variables to the url? Not only download?
@J.Doe this.router.navigate(['/chart', this.height, this.width, this.color]);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.