FormControl在Angular 2中返回空值

时间:2017-06-28 07:00:28

标签: angular angular2-forms angular2-services

我正在使用表格

<form [formGroup]="form">
    <input type="text" value={{userDetails.first_name}} formControlName = "firstName">
    <button type="submit" data-action="save" (click)="onSubmit(form.value)">
</form>

这里userDetails.first_name值是汤姆。它在文本框内的UI上可见;但是当我提交表格form.firstName给我空值时。

3 个答案:

答案 0 :(得分:0)

要获得该值,您应该检查form.value.firstName而不是form.firstName

要更好地了解表单的结构,请在表单上提交console.log(this.form)

答案 1 :(得分:0)

声明表单组:

private userForm: FormGroup;

初始化用户表单如下:

  userForm = form.group({
          firstName:  [firstName, [Validators.required]]
        });

以HTML格式声明您的表单:

 <form class="example-form " [formGroup]="userForm"
                  (ngSubmit)="onSubmit(userForm)">
    <input type="text" value={{userDetails.firstName}} formControlName = 
      "firstName">
    <button type="submit" data-action="save"/>
 </form>

使你的onSubmit()方法如下:

onSubmit({formValue, valid}: { formValue: UserDetails, valid: boolean }) {
    const firstName= value.firstName;
 }

答案 2 :(得分:0)

html

<form [formGroup]="form">
    <input type="text" formControlName="firstName">
    <button type="submit" data-action="save" (click)="onSubmit(form.value)">
</form>

<强>组件

你可以像这样设置值

this.form.patchValue({firstName:this.userDetails.first_name});

确保您将表单组的实例创建到组件