显示表单时如何在表单中显示本地存储的数据

时间:2019-06-03 12:45:40

标签: angular

我有一个注册表单,其中包含一些要存储在本地存储中的数据,并且希望在加载第二个表单时显示某些注册表单字段,例如名字和姓氏。此数据应来自本地存储。代码捕捉是第二种形式。

  onSubmit() {
  console.log(this.dataModel);`enter code here`
  this.submitted = true;
  this.registerService.firstdata(this.dataModel)
    .subscribe(
      data => console.log('Success!', data))

}
  ngOnInit() {
    this.userData = localStorage.getItem('user_data');
  }


 <input type="text" id="firstName" class="form-control" placeholder="First Name" name="firstName"
              [(ngModel)]="dataModel.firstName" #firstName="ngModel" required pattern="[a-zA-Z][a-zA-Z]+">
            </div>

 <input type="text" id="lastName" class="form-control" placeholder="Last Name" name="lastName"
              [(ngModel)]="dataModel.lastName #lastName="ngModel" required pattern="[a-zA-Z][a-zA-Z]+">
            </div>

2 个答案:

答案 0 :(得分:0)

如果您的本地存储包含名字和姓氏,则如下所示在ngOninit()中更新您的dataModel

ngOnInit() {
this.userData = localStorage.getItem('user_data');

// update first name and last name from local storage
this.dataModel.firstname =  this.userData.firstname; // get data here from local storage
this.dataModel.lastname =  this.userData.lastname; // get data here from local storage

}

希望这会对您有所帮助。

答案 1 :(得分:0)

您已经从ngOnInit的本地存储中获取数据,您只需要初始化dataModel字段即可。

ngOnInit() {
  this.userData = localStorage.getItem('user_data');

  this.dataModel.firstName = userData.firstName;  // <-- Assuming field name in localstorage as userData.firstName
  this.dataModel.lastName = userData.lastName;    // <-- Assuming field name in localstorage as userData.lastName 
}