I have a user form in my app. I create the form in my component in a Reactive Forms way. In some scenarios I want to set the form controls so they are disabled and the user cannot interact with them. My (reduced) code looks like so...

constructor(private usersService: UsersService, private formBuilder: FormBuilder) {}// I create the readonly booleanpublic isReadOnly: boolean=false;private buildMyForm(): void {this.userForm=this.formBuilder.group({StatusID: [{value: '', disabled: this.isReadOnly}, Validators.required],AddressID: [{value: '', disabled: this.isReadOnly}, Validators.required],Comments: [{value: '', disabled: this.isReadOnly}, Validators.maxLength(250)],Description: [{value: '', disabled: this.isReadOnly}, Validators.maxLength(250)],});}public ngOnInit(): void {this.buildForm(); // create the formthis.usersService.loadUser().subscribe((response:UserData)=> {// lots of info but we are interested in response.readonly which is a booleanif(response.readonly) {this.isReadOnly=response.readonly;}});}

As you can see I determine if the form should be read only once the usersService.loadUser() has returned a value, now by this time my formBuilder has already constructed the form and the disabled status will not be affected if the response.readonly is true. Should I move the this.buildForm(); into the subscription the app errors as the HTML wants the formBuilder [formGroup]="userForm". I've been reading on how I could update the form controls but nothing so far has worked, I thought I could use .patchValue like so

if(response.readonly) {this.isReadOnly=response.readonly;this.userForm.patchValue({// set the disabled status for StatusID, AddressID:, Comments:, Description});}

However I am unsure if this is the correct way to go about this... I am not wanting to update the value? I'm currently reading the docs but usually people here are much quicker than me so if anyone can help please point me in the right direction.

Before I forget - I know I can add a condition to my HTML template using [disabled]="isReadOnly" or [readonly]="isReadOnly", I just thought it would be a better approach to have the logic in the component, not the template...

share|improve this question

you can enable() to enable the disabled field

to enable field by control

this.userForm.controls.StatusID.enable();

or simply

this.userForm.enable();

will enable all the disabled fields

share|improve this answer

    I found out the answer, it was to set the items to disabled like so:

    if(response.readonly) {this.userForm.get('StatusID').disable();this.userForm.get('AddressID').disable();this.userForm.get('Comments').disable();this.userForm.get('Description').disable();}
    share|improve this answer

      Your Answer

       
      discard

      By posting your answer, you agree to the privacy policy and terms of service.

      Not the answer you're looking for? Browse other questions tagged or ask your own question.