Prashant Pimpale
Prashant Pimpale

Reputation: 10697

How to reset particular controls from FormGroup in angular 6

I am using FormGroup to take data from Frond end after submitting the form usually .reset() the method will reset all values from Controls.

1) I have five FormControls on my page but I want only to reset only 4 option, remaining 1 should be disabled with its already selected value.

2) Want to get rid of that Red-line (Error Class) which UI looks like:

enter image description here

What I have tried so far (If the formControl name is brand then disable):

ResetControls() method:

  for (var name in this.form.controls) {
      if (name != 'brand') {
        this.form.reset();
        (<FormControl>this.form.controls[name]).setValidators(Validators.compose([]))
        this.form.controls[name].setErrors(null);
      }
      else
      {
       // var value = (<FormControl>this.form.controls[name]).value;
        (<FormControl>this.form.controls[name]).markAsPristine();
        (<FormControl>this.form.controls[name]).markAsUntouched();
       this.form.get('brand').disable();  

      }
    }

FormGroup:

this.form = new FormGroup({
      brand: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      sku: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      cRate: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      pRate: new FormControl("", Validators.compose([
        Validators.required,
      ])),
      eDate: new FormControl("", Validators.compose([
        Validators.required,
      ])),
    });

3) Which reset all the option but unable to apply existing required field for every Control.

Upvotes: 0

Views: 6293

Answers (1)

Wendell
Wendell

Reputation: 180

You have to pass in the map of states that matches the form controls in your form.

const form = new FormGroup({

first: new FormControl('first name'),
  last: new FormControl('last name')
});

form.reset({
  first: {value: 'name', disabled: true},
  last: 'last'
});

console.log(this.form.value);  // {first: 'name', last: 'last name'}
console.log(this.form.get('first').status);  // 'DISABLED'

Upvotes: 2

Related Questions