如何使用以前保存的对象以角度电抗形式设置默认值?

时间:2019-11-13 22:35:35

标签: javascript angular forms reactive

我的反应形式即将完成。至少这是基本逻辑。我只有一个问题。根据任务,我需要使用用户输入的先前数据来设置所有输入,如果这些数据当然存在的话。如果切换了组件,则应保留,存储和呈现数据。我设法将所有数据保存到组件中的对象中,但是在页面刷新之后,所有内容都消失了。 我该如何解决这个问题?

我的代码如下:

    import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
    import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';

    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.scss']
    })
    export class FormComponent implements OnInit {
      signUpForm: FormGroup;
      countries = [
        new FormControl('USA'),
        new FormControl('India')
      ];

      savedForm: {
        city: string,
        code: number,
        country: string,
        email: string,
        firstName: string,
        id: string,
        lastName: string,
        phone: number,
        state: string;
      }

      statesUSA = [new FormControl('New York'), new FormControl('California')];
      statesIndia = [new FormControl('Andhra Pradesh'), new FormControl('Goa')]

      citiesNY = [new FormControl('Albany'), new FormControl('New York City')];
      citiesCali = [new FormControl('Sacramento'), new FormControl('Los Angeles'), new FormControl('San Francisco')];
      citiesAndhra = [new FormControl('Visakhapatnam'), new FormControl('Amaravati')];
      citiesGoa = [new FormControl('Panaji'), new FormControl('Vasco da Gama')];

      @ViewChild('phoneInput', {static: false}) phoneInput: ElementRef;
      public mask:any = {
        mask: '+{38}(0__)000-00-00',
        lazy: false
      }

      constructor() { }

      ngOnInit() {
        this.signUpForm = new FormGroup({
          'firstName': new FormControl(null, [Validators.required, Validators.pattern(/^[а-яА-ЯёЁіІїЇ]{2,32}$/iu)]),
          'email': new FormControl(null, [Validators.required, Validators.email, Validators.pattern(/^\S{2,255}@\S+\.\S+$/iu)]),
          'country': new FormControl(null, Validators.required),
          'phone': new FormControl(null),
          'lastName': new FormControl(null, [Validators.required, Validators.pattern(/^[а-яА-ЯёЁіІїЇ]{2,32}$/iu)]),
          'id': new FormControl(null, [Validators.required, Validators.pattern(/\b[A-Za-z_]{5,30}\b/)]),
          'state': new FormControl(null, Validators.required),
          'city': new FormControl(null, Validators.required),
          'code': new FormControl(null, [Validators.pattern(/\b[A-Za-z_0-9]{1,10}\b/)])
        });

        this.signUpForm.setValue(this.savedForm);
      }


      onBlur(blur: boolean) {

      }

      onSubmit() {
        if(this.signUpForm.status === 'VALID') {
          this.

savedForm = this.signUpForm.value;
      console.log(this.savedForm);
    }
  }

  onReset() {

  }

  onChange() {
   (<FormGroup>this.signUpForm.get('state').value) = null;
   (<FormGroup>this.signUpForm.get('city').value) = null;
  }

  onOpen(controlName: string) {
  }
}

1 个答案:

答案 0 :(得分:0)

您应该使用Service,组件不应直接获取或保存数据,而应专注于呈现数据并将数据访问权委派给服务。

第1步

创建服务:

src / services / storeService.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class StoreService {

  public savedForm

}

当您在根级别提供服务时,Angular会创建一个StoreService的单个共享实例,并将其插入任何需要它的类中。如果最终不使用服务,则在@Injectable元数据中注册提供程序还可以使Angular通过删除服务来优化应用程序。

第2步

在您的组件中,将新创建的服务注入到构造函数中:

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent {
  signUpForm: FormGroup;

  constructor(private storeService: StoreService) { }

  ngOnInit() {

    this.signUpForm = new FormGroup({
      'firstName': new FormControl(null, [Validators.required, Validators.pattern(/^[а-яА-ЯёЁіІїЇ]{2,32}$/iu)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.pattern(/^\S{2,255}@\S+\.\S+$/iu)]),
      'country': new FormControl(null, Validators.required),
      'phone': new FormControl(null),
      'lastName': new FormControl(null, [Validators.required, Validators.pattern(/^[а-яА-ЯёЁіІїЇ]{2,32}$/iu)]),
      'id': new FormControl(null, [Validators.required, Validators.pattern(/\b[A-Za-z_]{5,30}\b/)]),
      'state': new FormControl(null, Validators.required),
      'city': new FormControl(null, Validators.required),
      'code': new FormControl(null, [Validators.pattern(/\b[A-Za-z_0-9]{1,10}\b/)])
    });

    if (this.storeService.savedForm) this.signUpForm.setValue(this.storeService.savedForm)
  }

  onSubmit() {
    if (this.signUpForm.status === 'VALID') {
      this.storeService.savedForm = this.signUpForm
    }
  }
}