0

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].

1
  • Would you please share your code in codepen.io or something else? Commented Aug 8, 2022 at 18:08

3 Answers 3

1

You should use control.disable() or control.enable(), where control is your this.testForm.get('testControl')

Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

0

check this!

get address() {return this.profileForm.get('address') as FormGroup;}

updateProfile() {this.address.controls?.['city']?.setValue('123');}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.