Reputation: 11
I'm using Angular version 8 cli and I have two separate components. The first is a form component where I have a form, the user inputs information and hits submit, then I make a service api call to get a list of items matching those results and display them. Once the user chooses which line item they want to view, they click on the eventId and the application navigates to the second component where they can view the summary and pdfs associated with that line item. Also in this component 2 they will see a "Back to Results" button. What I want to do is save the user's inputs from the form on component 1 as they navigate to component 2 and then when they click on the "Back to Results" button, the app will navigate back to component 1 with the previous search inputs AND results loaded. I have tried using localstorage as well as trying to save to my service and nothing seems to be working. Can anyone help with this? I will paste some my code below. If you need any additional info, please let me know. Thanks in advance!!
<ng-container *ngFor="let item of items">
<tr>
<td scope="row">{{ item.validated }}</td>
<td><button class="nav-item nav-link" (click)="onSelectItem(item)">{{ item.eventID }}</button></td>
<td>{{ item.typeCode }}</td>
<td>{{ item.facilityname }}</td>
<td>{{ item.entrydate }}</td>
<td>{{ item.appID }}</td>
<td>{{ item.cinNumber }}</td>
<td>{{ item.lastName }},{{ item.firstName }}</td>
<td>{{ item.dob }}</td>
<td>{{ item.countycode }}</td>
<td>{{ item.aidCode }}</td>
</tr>
</ng-container>
</tbody>
**Component 1 form ts:**
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { RxwebValidators, ReactiveFormConfig, RxFormBuilder } from '@rxweb/reactive-form-validators';
import * as moment from 'moment';
import { Items } from './pdfs';
import { PdfApiService } from '../shared/services/api/pdf-api.service';
import { Facility } from '../shared/form';
import { Router } from '@angular/router';
@Component({
selector: 'app-cmsp-form',
templateUrl: './cmsp-form.component.html',
styleUrls: ['./cmsp-form.component.scss']
})
export class CmspFormComponent implements OnInit {
facility: Facility[] = [];
items: Items[] = [];
lineItem: {};
previousItems: any;
customerForm: FormGroup;
value: any[];
isValidFormSubmitted = false;
isLineItemsShown = false;
entrydate = moment(new Date()).format('YY-MM-DD');
minDate = new Date(1900, 1, 1);
maxDate = moment(new Date()).format('YY-MM-DD');
selectedItem: Items;
constructor(private formBuilder: RxFormBuilder, private pdfApiService: PdfApiService, private router: Router) {
}
loadFacilities() {
return this.pdfApiService.getFacilities().subscribe((res: Facility[]) => {
this.facility = res;
// console.log(this.facility);
});
}
buildForm() {
this.customerForm = this.formBuilder.group({
appID: ['', [RxwebValidators.digit(), RxwebValidators.maxLength({ value: 30 })]],
cinNumber: ['', [RxwebValidators.alphaNumeric(), RxwebValidators.minLength({ value: 9 }), RxwebValidators.maxLength({ value: 13 })]],
entrydate: [''],
lastname: ['', [RxwebValidators.required({ conditionalExpression: (x) => x.dob !== '' })]],
dob: ['', [RxwebValidators.required({ conditionalExpression: (x) => x.lastname !== '' })]],
facilitynpi: [''],
});
}
ngOnInit(): void {
this.loadFacilities();
this.buildForm();
this.previousItems = this.pdfApiService.searchResults;
ReactiveFormConfig.set({
'validationMessage': {
'required': 'This field is required.',
'digit': 'This field only accepts numbers.',
'alphaNumeric': 'This field only accepts letters and numbers.',
'minLength': 'This field must be 9-13 characters.',
'maxLength': 'This field must be 9-13 characters.'
}
});
}
omit_special_char(event: { charCode: any; }) {
let k: number;
k = event.charCode; // k = event.keyCode; (Both can be used)
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k === 8 || k === 32 || (k >= 48 && k <= 57));
}
// convenience getter for easy access to form fields
get f() { return this.customerForm.controls; }
onFormSubmit(event: { preventDefault: () => void; }) {
event.preventDefault();
this.isValidFormSubmitted = true;
if (this.customerForm.invalid) {
return;
}
this.getLineItems();
this.isLineItemsShown = true;
}
getLineItems() {
this.pdfApiService.getLineItems(this.customerForm.value).subscribe((res: Items[]) => {
this.items = res;
}, err => {
console.log(err);
});
}
onSelectItem(item) {
this.pdfApiService.selectedLineItem = item;
this.router.navigateByUrl('/results');
// console.log(this.pdfApiService.selectedLineItem);
}
private resetForm() {
this.isLineItemsShown = false;
this.customerForm.setValue({
appID: '',
cinNumber: '',
entrydate: '',
dob: '',
facilitynpi: 'Choose Facility',
lastname: ''
});
}
onFormReset() {
this.resetForm();
}
}
**Component 2 results html**
<div class="return-btn mt-2">
<a class="nav-item nav-link"><button type="button" class="btn btn-primary col-12 p-1 m-0" (click)="backToResults()">Return to results</button></a>
</div>
**Component 2 results ts**
import { Component, OnInit, ViewChild } from '@angular/core';
import { PdfApiService } from '../shared/services/api/pdf-api.service';
import { ModalService } from '../shared/services/modal.service';
import { Router } from '@angular/router';
import value from '*.json';
@Component({
selector: 'app-cmsp-results',
templateUrl: './cmsp-results.component.html',
styleUrls: ['./cmsp-results.component.scss']
})
export class CmspResultsComponent implements OnInit {
private bodyText: string;
lineItem: any;
previousItems: {};
pdfSrc: any;
page: number;
totalPages: number;
isPdfLoading: boolean;
pdfToShow: any;
keys: any;
constructor(private modalService: ModalService, private pdfApiService: PdfApiService, private router: Router) {
// console.log(this.pdfApiService.selectedLineItem);
// console.log(this.pdfSrc);
}
ngOnInit() {
this.lineItem = this.pdfApiService.selectedLineItem;
this.pdfApiService.getKeys(this.pdfApiService.selectedLineItem.APPKEY).subscribe(res => {
this.keys = res;
// console.log(this.keys);
// this.createPdfFromBlob(data);
// const file = new Blob([data], { type: 'application/pdf' });
// const fileURL = URL.createObjectURL(file);
// window.open(fileURL);
this.isPdfLoading = true;
}, error => {
this.isPdfLoading = false;
console.log(error);
});
this.bodyText = 'This text can be updated in modal 1';
}
onSelectedFile(key) {
this.pdfApiService.getPdf(key).subscribe(data => {
// console.log(data);
const file = new Blob([data], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(file);
// window.open(fileURL);
this.pdfSrc = fileURL;
// console.log(fileURL);
});
}
backToResults(item: any) {
this.pdfApiService.searchResults = item;
this.router.navigateByUrl('/');
console.log(this.pdfApiService.searchResults);
}
createPdfFromBlob(pdf: Blob) {
const reader = new FileReader();
reader.addEventListener('load', () => {
this.pdfToShow = reader.result;
}, false);
if (pdf) {
reader.readAsArrayBuffer(pdf);
}
}
openModal(id: string) {
this.modalService.open(id);
}
closeModal(id: string) {
this.modalService.close(id);
}
}
Upvotes: 1
Views: 163
Reputation: 149
You can use the same method as you are passing the information to second component. you can save data from first component in this.pdfApiService and when you init first component then you can check for information in service and load into first component.
You can use notification service to send info back to first component from second component.
Upvotes: 1