Issue
I want to see the plan data that was selected on the previous screen and then submit the form with all the data. What is the best way to do this in Angular?
It is showing objects instead of actual data in params as you can see in the console.
import { FormModel } from './../../shared/model';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ApiService } from './../../shared/api.service';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
query: any;
form: FormModel;
constructor(
public apiService: ApiService,
public actRoute: ActivatedRoute,
public router: Router
) {
this.form = new FormModel();
}
ngOnInit() {
this.query = this.actRoute.queryParams.subscribe(params => {
console.log(params);
});
}
enviar(): void {
console.log(this.form);
this.resetForm();
}
resetForm() {
this.form = new FormModel();
}
}
passing parameters directly on the link to the page.
<h2>Escolha um plano</h2><br>
<div class="row">
<div class="col-md-4" *ngFor="let pl of planoTablet.planos" #card>
<div class="card w-100">
<div class="card-body">
<div class="float-left">
<h5 class="card-title">{{ pl.franquia }}</h5>
<p class="card-text">R$ {{ pl.valor }}</p>
</div>
<a routerLink="/plataformas/planos/form/{{pl.sku}}/"
[queryParams]="planoTablet.planos" class="btn btn-danger btn-
lg float-right mt-2" [ngClass]="{'disabled': pl.ativo ==
false}">Contratar</a>
</div>
</div><br>
</div>
</div>
the goal is to show data from the plan that was previously chosen
Solution
It is generally not a good idea to pass complex(nested) objects to you url because they may not be encoded properly. I better aproach will be to create a service to share data between components.
Simple(flat) Objects:
If you are using simple(flat) objects to send through queryParams
that's fine.
You can send them like this:
<a routerLink="yourRoute" [queryParams]="{param1: 'hello', param2: 'world'}">Contratar</a>
Complex Objects
For the complex object you can create a service. It would be something like this:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharingService {
sharingObject: any;
constructor() { }
set sharedValue(obj) {
this.sharingObject = obj
}
get sharedValue() {
return this.sharingObject
}
}
I've created a demo for you that uses service to share data among components.
Answered By - asimhashmi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.