[javascript] Angular 2: Passing Data to Routes?

I am working on this angular2 project in which I am using ROUTER_DIRECTIVES to navigate from one component to other.

There are 2 components. i.e. PagesComponent & DesignerComponent.

I want to navigate from PagesComponent to DesignerComponent.

So far its routing correctly but I needed to pass page Object so designer can load that page object in itself.

I tried using RouteParams But its getting page object undefined.

below is my code:

pages.component.ts

import {Component, OnInit ,Input} from 'angular2/core';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
import { ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';
import { DesignerComponent } from './../../designer/designer.component';
import {RouteParams} from 'angular2/router';

@Component({
    selector: 'pages',    
    directives:[ROUTER_DIRECTIVES,],
    templateUrl: 'app/project-manager/pages/pages.component.html'
})
@RouteConfig([
  { path: '/',name: 'Designer',component: DesignerComponent }      
])

export class PagesComponent implements OnInit {
@Input() pages:any;
public selectedWorkspace:any;    
constructor(private globalObjectsService:GlobalObjectsService) {
    this.selectedWorkspace=this.globalObjectsService.selectedWorkspace;                    
}
ngOnInit() { }   
}

In the html, I am doing following:

<scrollable height="300" class="list-group" style="overflow-y: auto; width: auto; height: 200px;" *ngFor="#page of pages">
    {{page.name}}<a [routerLink]="['Designer',{page: page}]" title="Page Designer"><i class="fa fa-edit"></i></a>
</scrollable>

In the DesignerComponent constructor I have done the following:

constructor(params: RouteParams) {
    this.page = params.get('page');
    console.log(this.page);//undefined
}

So far its routing correctly to designer, but when I am trying to access page Object in designer then its showing undefined. Any solutions?

This question is related to javascript typescript angular angular2-routing

The answer is


1. Set up your routes to accept data

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2. Navigate to route:

From HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

Or from Typescript:

import {Router} from '@angular/router';

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3. Get data from route

import {ActivatedRoute} from '@angular/router';

...

this.value = this.route.snapshot.params['key'];

It changes in angular 2.1.0

In something.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

To get the data or params in edit component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

You can do this:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

So you can get the data by this.route.snapshot.data['name'].


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular2-routing

'router-outlet' is not a known element How to reload page the page with pagination in Angular 2? Error: Cannot match any routes. URL Segment: - Angular 2 Can't bind to 'routerLink' since it isn't a known property Passing data into "router-outlet" child components How to determine previous page URL in Angular? How to get parameter on Angular2 route in Angular way? Angular 2 Scroll to top on Route Change Angular routerLink does not navigate to the corresponding component Angular 2 router.navigate