我有一个有角度的2(稳定版)应用程序(带有表单的多个页面),当用户填写表单并使用提交转到下一页我更新服务对象(表单值firstname:value,lastname:值等)并且用户被导航到下一页(表单)。
用户进入下一页后,将使用上一页收集的值更新服务对象。但是,如果用户点击后退按钮或单击链接返回上一页,则表单为空。我希望能够填充服务对象中收集的值。我试过阅读angular2中4种不同的绑定方式,但它似乎没有用。我尝试使用* ngIf查看是否可以检查服务对象属性,如果用户通过后退按钮或提供的链接导航回上一页,则重新填充表单。请注意我没有错误。只是不了解如何绑定工作。任何有关如何解决这个问题的帮助表示赞赏。
这是我的组件和相关的Html模板(片段) 的启动component.ts
import { Component, OnInit } from '@angular/core';
import {UserService} from '../services/user-service';
import { Router } from '@angular/router';
@Component({
selector: 'app-start',
templateUrl: './start.component.html',
styleUrls: ['./start.component.css']
})
export class StartComponent implements OnInit {
constructor(
private _userSerivce: UserService,
private _router: Router,
) {
console.log(_userSerivce);
}
ngOnInit() {
}
startSubmitted: boolean = this._userSerivce.startComplete;
onSubmit(value: any){
//console.log(value);
this._userSerivce.startComplete = true;
this._userSerivce.start = value;
console.log(this._userSerivce.startComplete);
console.log(this._userSerivce.start);
this._router.navigate(['personal']);
}
}
来自 Start.component 模板的片段
<div class="container">
<div class="row">
<app-side-nav-bar></app-side-nav-bar>
<div class="col-sm-7">
<h1>Start</h1>
<form autocomplete='off' novalidate #form="ngForm"(ngSubmit)="onSubmit(form.value)">
<div class="form-group row">
<div class="col-sm-8">
<label for="firstName">First Name</label>
<input
class="form-control" type="text"
required
name="firstName"
([ngModel])='firstName'
[value]='firstName'
>
</div>
</div>
<div class="lg-pad"></div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit">Submit</button>
</div>
</div>
<div>
答案 0 :(得分:-1)
因此,当用户从一个页面前进到另一个页面时,将使用用户键入的值更新服务。如果他们点击后退按钮,则ngInit会查找服务中的值并更新表单。这真的很简单。此外,我还实现了本地存储来存储表单值。