Glenn Utter
Glenn Utter

Reputation: 2363

Angular 2: Resetting form ignores initial value

I have an Angular 2 app where I set default values for certain inputs like this:

this._stdSearchForm = this._formBuilder.group({
    count: [{value: 50, disabled: false}, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.pattern("^[0-9]+$")])]
});

I have inplemented a "reset" feature like this:

(click)="resetStdSearchForm()"

and that just runs:

this._stdSearchForm.reset();

That resets the form, but ignores the initial value defined in the FormBuilder group.

Is this behaviour intended?

Can I programatically set the value of "count" after resetting the form? I tried doing this:

this._stdSearchForm.value.count = 50;

but that changed nothing.

Upvotes: 15

Views: 11339

Answers (1)

yurzui
yurzui

Reputation: 214047

You can try the following:

this._stdSearchForm.setValue({ count: 50});

or you can do the same by:

this._stdSearchForm.reset({ count: 50});

The reset method resets the FormGroup. This means by default:

  • The group and all descendants are marked pristine
  • The group and all descendants are marked untouched
  • The value of all descendants will be null or null maps

Upvotes: 19

Related Questions