我正在尝试将一个组件路由到另一个组件;每个组件都有一些表单数据(this.formBuilder.group
)。当我从一个组件导航到另一个组件时,如果回到上一个组件,则填充的数据将无法恢复。
在路由每个组件之前,有什么方法可以保存数据吗?在离开组件以保存所有表单数据之前,是否有任何生命周期方法可以检测?
navigation.ts:
if(currentNav == "Personal Details"){
this.router.navigateByUrl('/understand/personal');
} else if(currentNav == "Contact Details"){
this.router.navigateByUrl('/understand/contact');
}
contact.ts
ngOnInit() {
this.contactDetails = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
mobileNumber: ['', Validators.required],
secondaryNumber: ['', Validators.required]
});
}
personal.ts
this.personalDetails = this.formBuilder.group({
country: ['', Validators.required],
countryOfIssue: ['', Validators.required],
countryOfBirth: ['', Validators.required]
});
}
答案 0 :(得分:0)
将在全局服务中每个组件中捕获的数据持久化,并在来回移动时将其恢复。您可以在构造函数或ngOnInit方法中分配全局服务对象。如下所示:
home.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { GlobalService } from'../global.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
homeDetails: FormGroup;
constructor(private formBuilder: FormBuilder,private globalService: GlobalService) {
this.homeDetails = this.formBuilder.group({
homename:['', Validators.required]
});
}
ngOnInit() {
if(this.globalService.homeDetails){
this.homeDetails = this.globalService.homeDetails;
}
}
ngOnDestroy() {
this.globalService.homeDetails = this.homeDetails;
}
}
global.service.ts
import { FormGroup } from '@angular/forms';
import { Injectable } from '@angular/core';
@Injectable()
export class GlobalService {
public homeDetails: FormGroup;
public aboutDetails: FormGroup;
}
在移至另一个组件之前,您可以查看OnDestroy来实现任何代码。
已更新:根据stackblitz网址的home.component.ts和global.service.ts代码
答案 1 :(得分:0)
您可能会决定在退出组件上使用CanDeactivate Route Guard,而不是生命周期方法,这使您能够添加诸如保存和取消之类的功能。有关信息,请尝试https://v5.angular.io/guide/router#candeactivate-handling-unsaved-changes。