首页 文章

Angular - FormControl未正确绑定到formControlName

提问于
浏览
0

我正在使用 FormGroup & FormControl 手动创建一个表单模型,它很好,但是当angular将我的 FormControl 绑定到它对应的输入时,我得到一个意想不到的结果 .

我创建模型,并以这种方式绑定到HTML .

private initFormModel(user: User): FormGroup {
  const _formGroup = new FormGroup({
    fullname: new FormControl({ value: user.name })
  });
  return _formGroup;
}
<!-- This is part of the html code / I set on my component class this.form = this.initFormModel(... -->

<form (ngSubmit)="onSubmit()" [formGroup]="form" novalidate>

<!-- .... --->

<input type="text" formControlName="fullname" name="fullname">

Result

enter image description here

没有错,如果你希望我使用 FormBuilder 它不会改变任何东西 . 我得到 [Object object] 绑定到我的输入,有趣的是,如果我将禁用属性添加到我的表单控件定义,它将很好地工作 . 喜欢: fullname: new FormControl({ value: user.name, disabled: false }) 我得到了文本绑定,也是如果我使用数组表示法来创建FormControl( fullname: [user.name, ...] ) .

Just in case I'm currently using Angular v2.4.10

1 回答

  • 2

    the documentation

    实例化FormControl时,可以传入初始值作为第一个参数 . 例:

    const ctrl = new FormControl('some value');
    

    您还可以在实例化时使用表单状态对象初始化控件,其中包括值和是否禁用控件 . 没有禁用键,您不能使用值键;两者都需要使用这种初始化方式 .

    const ctrl = new FormControl({value: 'n/a', disabled: true});
    

    (强调我的)

相关问题