Reputation: 5407
I'm creating a form model manually using FormGroup & FormControl
, it's fine, but I get an unexpected result when angular binds my FormControl
to the input it corresponds.
I create the model, and bind to the html this way.
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
There's nothing wrong, if you expect me to use FormBuilder
it does not change anything. I got [Object object]
binded to my input, the funny thing is that If I add disabled attribute to my form control definition, it will work well. Like: fullname: new FormControl({ value: user.name, disabled: false })
I got the text binded, also If I use the Array notation to create the FormControl (fullname: [user.name, ...]
).
Just in case I'm currently using Angular v2.4.10
Upvotes: 0
Views: 4795
Reputation: 691625
From the documentation:
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});
(emphasis mine)
Upvotes: 2