简体   繁体   English

将预填充值传递到Angular 2反应形式输入的最佳方法

[英]Best way to pass pre-populated values to Angular 2 reactive form input

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)]),
    });
  }

}

I know it's probably a really simple fix, I'm just not seeing it. 我知道这可能是一个非常简单的修复程序,但我只是没有看到它。 I have my reactive formControl's in my ngOnInit but I need to pass preset values into each input (which is this.firstName , this.lastName , etc.). 我在我的我的反应性formControl的ngOnInit但我需要预设值传递到每个输入(这是this.firstNamethis.lastName等)。 When the view loads, the inputs are empty. 视图加载时,输入为空。

I believe the values aren't showing up because the form is loading before the values are populated. 我相信这些值不会显示出来,因为在填充值之前先加载表单。 Any ideas on how to fix this? 有想法该怎么解决这个吗?

You would be right. 你说的没错。 ngOnInit is already done before your getCurrentUserInfo is finished receiving data from your service. 在getCurrentUserInfo从服务接收数据之前,已经完成ngOnInit。 It is working asynchronously to avoid slowing down the application. 它是异步工​​作的,以避免降低应用程序的速度。

You either need to apply an observable to watch when your asynchronous request is done and the data is loaded or you can simply set your user new FormGroup inside of the "then" like this: 您要么需要应用一个observable来监视异步请求完成并加载数据的时间,要么可以在“ 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)]),
    });
})

Better yet, you can create a new method for reusability: 更好的是,您可以创建一种可重用性的新方法:

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)]),
    });
}

And call that method inside the "then". 并在“ then”内部调用该方法。

Solved the issue using Angular 2's setValue. 使用Angular 2的setValue解决了该问题。 Example code solution: 示例代码解决方案:

this.user.setValue({fname: this.firstName, lname: this.lastName, phone: this.phone, bio: this.bio});

You can use setValue if the control is already created or use it in constructor 如果控件已经创建,则可以使用setValue ,也可以在构造函数中使用它

new FormControl('your value',

I know that you can fix it some way because you know reactive form well but the value is pre-populated in this way. 我知道您可以通过某种方式修复它,因为您非常了解反应形式,但是值是以这种方式预先填充的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM