Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable or setting a variable by URL in Angular 2

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);
like image 441
J.Doe Avatar asked Mar 15 '17 21:03

J.Doe


1 Answers

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'];
      }
    );
  }
like image 105
Julian Avatar answered Nov 19 '22 08:11

Julian