Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Reactive Forms, formName.reset() works but throws error 'control.value is null' and all fields are marked 'red' and invalid?

I have an angular reactive form and on submit I have this code:

(ngSubmit)="addVideo(); addVidForm.reset();"

I am marking my main form with #addVidForm

I also have some custom validators/controls which is special vs another form that I have where this does not occur when resetting the form.

My validator is as follows:

 static mustBeVimeo(control: AbstractControl) : ValidationErrors | null {

        if((control.value as string).startsWith("https://vimeo.com/")){ return null } else
        if((control.value as string).startsWith("http://vimeo.com/")){ return null }
        else { return { mustBeVimeo : true } }

}

This is my form on the backend:

this.addVideoForm = new FormGroup({
      title: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
      description: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(200)]),
      category: new FormControl('', [Validators.required]),
      link: new FormControl('', [Validators.required, AddVideoValidators.mustBeVimeo, Validators.maxLength(100)]),
      visibleToGuests: new FormControl(this.visibleToGuests, [Validators.required])
    })

I have also made a function that just resets the form on the backend and call that with a button and I'm getting the same error.

Not entirely sure which part of this whole thing is failing. That field is a normal input like I'm using in other places.

like image 942
SebastianG Avatar asked Nov 17 '22 22:11

SebastianG


1 Answers

For Reactive Form you need to use [formGroup] attribute Binding. It exposes reset() public method.

Template:

<form [formGroup]="registerForm">
.....
</form>

Component:

this.registerForm.reset();
this.registerForm.markAsPristine();
this.registerForm.markAsUntouched();

You can also pass Empty values to the Form Values.

this.registerForm.reset(this.registerForm.value);
like image 116
Suresh Kumar Ariya Avatar answered Jan 06 '23 01:01

Suresh Kumar Ariya