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].
CodePudding user response:
You should use control.disable()
or control.enable()
, where control
is your this.testForm.get('testControl')
CodePudding user response:
use the disable() or enable() method.
testForm = this.fb.group({
testControl: ['123', {disabled: true}],
});
this.profileForm.get('address.city')?.setValue('abcdefg');
this.profileForm.get('address.city')?.disable()
CodePudding user response:
check this!
get address() {return this.profileForm.get('address') as FormGroup;}
updateProfile() {this.address.controls?.['city']?.setValue('123');}