Issue
I am using the FormBuilder
module to create a strictly typed reactive form, but I am only able to get values to display correctly when I don't need to specify whether or not the control is disabled. For example, if I have the following:
TS:
testForm = this.fb.group({
testControl: '123',
});
HTML:
<input formControlName="testControl" type="text">
Then the input displays the value 123
as expected and I can successfully update the value with setValue
. However, if I change the typescript code to:
testForm = this.fb.group({
testControl: [{ value: '123', disabled: true}],
});
Then it defaults to the correct value, but if I ever need to change it with setValue
or patchValue
, it begins displaying as [object Object]
.
Is testControl: [{ value: '123', disabled: true}]
not the correct way to initialize a control that can be disabled? Is this.testForm.get('testControl').setValue({ value: 'abcdefg', disabled: false })
not the correct way to update the value? What am I doing wrong?
I've also tried this.testForm.get('testControl').setValue('abcdefg')
when updating the value, but my IDE complains that a string isn't assignable to parameter of type { value: string; disabled: boolean; }
.
You can mess around with a similar example here: https://stackblitz.com/edit/angular-ntcvra?file=src/app/profile-editor/profile-editor.component.ts
You'll just have to click the "Profile Editor" button, then click "Update Profile" at the bottom and you'll see the city input change to [object Object].
Solution
You should use control.disable()
or control.enable()
, where control
is your this.testForm.get('testControl')
Answered By - Drenai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.