Angular - FormControl 未正确绑定到 formControlName
Angular - FormControl is not binding to formControlName correctly
我正在使用 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">
结果
没什么问题,如果你希望我使用 FormBuilder
它不会改变任何东西。我将 [Object object]
绑定到我的输入,有趣的是,如果我将 disabled 属性添加到我的表单控件定义中,它将运行良好。比如:fullname: new FormControl({ value: user.name, disabled: false })
我绑定了文本,如果我使用数组表示法创建 FormControl (fullname: [user.name, ...]
)。
以防万一我目前正在使用 Angular v2.4.10
When instantiating a FormControl, you can pass in an initial value as the first argument. Example:
const ctrl = new FormControl('some value');
You can also initialize the control with a form state object on instantiation, which includes both the value and whether or not the control is disabled. You can't use the value key without the disabled key; both are required to use this way of initialization.
const ctrl = new FormControl({value: 'n/a', disabled: true});
(强调我的)
我正在使用 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">
结果
没什么问题,如果你希望我使用 FormBuilder
它不会改变任何东西。我将 [Object object]
绑定到我的输入,有趣的是,如果我将 disabled 属性添加到我的表单控件定义中,它将运行良好。比如:fullname: new FormControl({ value: user.name, disabled: false })
我绑定了文本,如果我使用数组表示法创建 FormControl (fullname: [user.name, ...]
)。
以防万一我目前正在使用 Angular v2.4.10
When instantiating a FormControl, you can pass in an initial value as the first argument. Example:
const ctrl = new FormControl('some value');
You can also initialize the control with a form state object on instantiation, which includes both the value and whether or not the control is disabled. You can't use the value key without the disabled key; both are required to use this way of initialization.
const ctrl = new FormControl({value: 'n/a', disabled: true});
(强调我的)