Nikolai
Nikolai

Reputation: 672

How to reset ng-select in Reactive Form through a FormGroup (AbstractControl) in Angular 9?

I have a FormGroup with a bunch of ng-select elements. I also have the following code that resets all of the values in the Reactive Form except the ng-select elements.

  Object.keys(this.myFormGroup.controls).forEach(key => {
    const currentControl = this.myFormGroup.controls[key];
    if (currentControl == null) {
      currentControl.reset();
    }
  });

I tried also currentControl.patchValue('') and with null, but it doesn't work. When I load a wrong "item" in the ng-select it has a selected value "undefined" and I want to clear this default selected value when it is undefined. That's why I use == null.

Even if you have a hacky JavaScript (Vanilla) solution, share it.

Upvotes: 0

Views: 783

Answers (1)

Ali Jamal
Ali Jamal

Reputation: 619

Did you try to pass the initial value you want to reset the ng-select to; inside the reset function like so?

    Object.keys(this.myFormGroup.controls).forEach(key => {
    const currentControl = this.myFormGroup.controls[key];
    if (currentControl == (null || undefined)) {
      currentControl.reset('');
    }
  });

I also added check for undefined control value too.

Upvotes: 0

Related Questions