Pass an object as a parameter to another Component using Angular 2?

Asked

Viewed 11,462 times

1

I’m a beginner in Angular 2 and need to open a page (Component) and pass an object to it. Routes are mapped and in function calcularResultado, need to send the questoes object to the Component defined on the "/result route"

import { Component, OnInit } from '@angular/core';

import { QuestoesService } from "./questoes.service";

import { Router, NavigationExtras } from "@angular/router";

    @Component({
        selector: 'app-questoes',
        templateUrl: './questoes.component.html',
        styleUrls: ['./questoes.component.css']
    })
    export class QuestoesComponent implements OnInit {

        questoes:any = new QuestoesService().getQuestoes();

        questaoSelecionada: any;
        questaoSelecionadaIndex: number = 0;
        router:Router;

        constructor(router: Router) {
            this.router = router;
            this.questaoSelecionada = this.questoes[0];
        }

        ngOnInit() {

        }

        avancar(){
            this.questaoSelecionadaIndex++;
            this.questaoSelecionada =  this.questoes[this.questaoSelecionadaIndex];
        }

        voltar(){
            this.questaoSelecionadaIndex--;
            this.questaoSelecionada =  this.questoes[this.questaoSelecionadaIndex];
        }

        calcularResultado(questoes){
            this.router.navigateByUrl("/resultado");
        }
    }

2 answers

4


You can use the directive:

routerLink="/resultado" [queryParams]="questoes"

or via code:

calcularResultado(){
    this.router.navigate(['/resultado'], 
      {queryParams: this.questoes});
}

or

calcularResultado(){
    let navigationExtras: NavigationExtras = {
      queryParams: this.questoes,
      //fragment: 'anchor',
      //preserveQueryParams: true,
      //preserveFragment: true
    };
    this.router.navigate(['/resultado'], 
      {queryParams: this.questoes});
}

https://angular.io/docs/ts/latest/guide/router.html#! #query-Parameters

2

To access the parameter in the target Component

  constructor(private route: ActivatedRoute) {
  }

  ngOnInit() {
    // se possivel, capture o parametro 
    let questoesParam = this.route
      .queryParamMap
      .map(params => params.get('atributo') || 'None');
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.