表单字段Angular 4中的默认值

时间:2018-03-24 17:56:00

标签: angular angular4-forms

当数据来自服务时,表单字段值需要初始化。 我正在使用Reactive Form(表单构建器)。

我想要的只是从表格中获取所有数据,即使它在提交后是否更新。

数据来自getProfile()函数,该函数在ngOnInit()中调用。

提交表单后,只有(this.form)对象中提供了更新的字段数据,但所有来自 userData 的数据都会被忽略。

因此我的表格永远无效。

    async getProfile() {
            const observable = await this.userService.getProfile();
            observable.subscribe((res: any) => {
              this.userData= res.data;
            });
          }

      ngOnInit() {
        this.getProfile();
        this.user= {};

        this.form = this.formBuilder.group({
          firstName: ['', [

            Validators.pattern(new RegExp('^[a-zA-ZäöüÄÖÜ]*$'))
          ]],
          lastName: ['', [

            Validators.pattern(new RegExp('^[a-zA-ZäöüÄÖÜ]*$'))
          ]],
          email: ['', [
            Validators.email
          ]],
          city: ['', Validators.required],
          postalCode: ['', [

            Validators.minLength(5)
          ]],
          address1: [''],
          address2: '',
        });

      }

模板

<form *ngIf="form" [formGroup]="form" (ngSubmit)="saveUser()" novalidate>
          <div class="row">
            <div class="col-sm-6">
              <div class="form-group">
                <label for="firstName">First name</label>
                <div class="input-group input-group-sm">
                  <input type="text" class="form-control" id="firstName" name="firstName" value="userData?.firstname" formControlName="firstName" placeholder="Your First Name">
                </div>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label for="lastName">Last name</label>
                <div class="input-group input-group-sm">
                  <input type="text" class="form-control" id="lastName" value="{{userData?.lastname}}" name="lastName" formControlName="lastName" placeholder="Your Last Name">
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-sm-12">
              <div class="form-group">
                <label for="postalCode">Email</label>
                <div class="input-group input-group-sm">
                  <input type="email" class="form-control input-sm" value="{{userData?.email}}" id="email" name="email" formControlName="email" placeholder="Your Email">
                </div>
              </div>
            </div>
          </div>
       </div>
      <br>
      <br>
      <br>
      <br>

      <button [disabled]="form.pristine" type="submit" class="btn btn-grad btn-tn">Update</button>
    </form>

Here is form view after page load

1 个答案:

答案 0 :(得分:0)

您没有在响应到达后更新表单。试试这个:

observable.subscribe((res: any) => {
  this.form.patchValue(res.data);
});