1

I've a simple form group, with 2 form controls. Initially both the controls have required validation.

I also have a button in the template. When clicking the button, i want to change the behavior of the form group. ie., Both the controls need to be disabled & and the validation needs to be removed.

StackBlitz

import {
  Component,
  AfterViewInit,
  ViewChild
} from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  name = 'Angular 6';

  form: FormGroup;

  constructor(private fb: FormBuilder) {

    let username = this.fb.control.apply(null, [{
      value: 'gannr',
      disabled: false
    }, Validators.required])

    let password = this.fb.control.apply(null, [{
      value: 'hello',
      disabled: false
    }, Validators.required]);

    this.form = this.fb.group({
      username: username,
      password: password
    });


  }


  changeFormBehavior() {

    let username = this.fb.control.apply(null, [{
      value: 'gannr disabled',
      disabled: true
    }]);

    let password = this.fb.control.apply(null, [{
      value: 'hello',
      disabled: true
    }]);

    this.form = this.fb.group({
      username: username,
      password: password
    });

  }



}

1
  • Could I know why you unmarked your answer as resolved ? Commented Aug 8, 2018 at 10:55

1 Answer 1

6

Maybe if you used the correct variables and syntax ...

  changeFormBehavior() {
    this.form.get('username').disable();
    this.form.get('password').disable();
    this.form.get('username').setValidators(null);
    this.form.get('password').setValidators(null);
 }

Stackblitz

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

12 Comments

Thanks for your answer. Why the form status is invalid even after removing the validation ?
nope. it didn't work. i also tried clearing the validation by calling clearValidators method
I see that, let me find out why for a second
It's not valid because it's empty (disabling a controls removes it from the value of the form). Remove this.form.updateValueAndValidity() and this.form.get('password').disable(), and it becomes valid. Stackblitz : stackblitz.com/edit/…
Is there any workaround to have all the formcontrol's disabled and still get the form to be valid ?
|

Your Answer

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