angular - 将预填充值传递给 Angular 2 响应式(Reactive)表单输入的方法是什么

标签 angular typescript angular-reactive-forms

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

import { User } from '../account.interface';
import { AF } from '../angularfire.service';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.less']
})
export class AccountComponent implements OnInit {
  public error: any;
  user: FormGroup;
  onSubmit() {
    console.log(this.user.value, this.user.valid);
  }

  currentUserDetails = [];
  firstName: string = '';
  lastName: string = '';
  email: string = '';
  phone: string = '';
  bio: string = '';
  userID: string = '';

  constructor(private afService: AF) {
    // Get current user details and push to array.  This is due to input values overwriting ngModels.
    afService.getCurrentUserInfo().then(currentUserDetails => {
      let currentUser = [];
      currentUser.push(currentUserDetails);
      this.firstName = currentUser[0].firstName;
      this.lastName = currentUser[0].lastName;
      this.email = currentUser[0].email;
      this.phone = currentUser[0].phone;
      this.bio = currentUser[0].bio;
      this.userID = currentUser[0].userID;
    }).then(() => {

    })
  }

  // Update the user details with the form entry.
  // updateUserEntry(firstName, lastName, phone, bio) {
  //   this.afService.updateUserEntry(this.userID, firstName, lastName, phone, bio).then(() => {
  //     location.reload();
  //   }).catch((error) => {
  //     this.error = error;
  //     console.log("error");
  //   });
  // }

  ngOnInit() {
    this.user = new FormGroup({
      fname: new FormControl(this.firstName, [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      lname: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      phone: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      bio: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(50)]),
    });
  }

}

我知道这可能是一个非常简单的修复,只是我没有看到它。我的 ngOnInit 中有我的响应式(Reactive) formControl,但我需要将预设值传递到每个输入(即 this.firstNamethis.lastName 等)。加载 View 时,输入为空。

我认为这些值没有显示,因为在填充值之前加载了表单。关于如何解决此问题的任何想法?

最佳答案

你是对的。在您的 getCurrentUserInfo 完成从您的服务接收数据之前,ngOnInit 已经完成。它异步工作以避免降低应用程序的速度。

您要么需要应用一个可观察对象来观察您的异步请求何时完成并加载数据,要么您可以像这样在“then”中简单地设置您的用户新 FormGroup:

afService.getCurrentUserInfo().then(currentUserDetails => {
    let currentUser = [];
    currentUser.push(currentUserDetails);
    this.firstName = currentUser[0].firstName;
    this.lastName = currentUser[0].lastName;
    this.email = currentUser[0].email;
    this.phone = currentUser[0].phone;
    this.bio = currentUser[0].bio;
    this.userID = currentUser[0].userID;

    this.user = new FormGroup({
      fname: new FormControl(this.firstName, [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      lname: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      phone: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      bio: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(50)]),
    });
})

更好的是,您可以创建一个可重用性的新方法:

SetFormGroup() {
    this.user = new FormGroup({
      fname: new FormControl(this.firstName, [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      lname: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      phone: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(24)]),
      bio: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(50)]),
    });
}

然后在“then”中调用该方法。

关于angular - 将预填充值传递给 Angular 2 响应式(Reactive)表单输入的方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44596602/

相关文章:

node.js - 通过 Webpack(终端)执行 Typescript Jasmine 测试以测试 Angular2

Angular2 react 形式根据验证失败条件显示错误消息

html - Angular2 动态生成响应式表单

Angular + NET 核心 "Http failure response for (unknown url): 0 Unknown Error"

angular - 如何在 *ngFor 中设置唯一的模板引用变量? ( Angular )

Angular 形式 : validate complete form group if a single value changes

typescript 对象类型到数组类型

javascript - 如何将数组键索引映射到下拉列表表单控件中的其他键名称?

javascript - Angular 2.如何将组件替换或包含到文本中

angular - 'Observable<英雄[] >' is not assignable to type ' 英雄[]'