[英]Reusable angular component has same data as previous one - input datalist
[英]Angular 8 - load form data input into previous component
我正在使用 Angular 版本 8 cli,我有兩個單獨的組件。 第一個是一個表單組件,其中我有一個表單,用戶輸入信息並點擊提交,然后我進行服務 api 調用以獲取與這些結果匹配的項目列表並顯示它們。 一旦用戶選擇了他們想要查看的行項目,他們點擊 eventId 並且應用程序導航到第二個組件,他們可以在其中查看與該行項目關聯的摘要和 pdf。 同樣在此組件 2 中,他們將看到“返回結果”按鈕。 我想要做的是在用戶導航到組件 2 時從組件 1 的表單中保存用戶的輸入,然后當他們單擊“返回結果”按鈕時,應用程序將使用先前的搜索輸入導航回組件 1 和結果加載。 我嘗試使用 localstorage 並嘗試保存到我的服務中,但似乎沒有任何效果。 有人能幫忙嗎? 我將在下面粘貼一些我的代碼。 如果您需要任何其他信息,請告訴我。 提前致謝!!
<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);
}
}
您可以使用與將信息傳遞給第二個組件相同的方法。 您可以將來自第一個組件的數據保存在 this.pdfApiService 中,當您初始化第一個組件時,您可以檢查服務中的信息並加載到第一個組件中。
您可以使用通知服務將信息從第二個組件發送回第一個組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.