Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a field from a Angular Reactive Form?

The Angular form I want to sent to the Api has 4 fields: username, email, password and confirmpassword. I want to send to the APi only three of them: username, email and password.

Any ideas how to delete the confirmpassword from the object?

Thank you!

This is how the object looks like:

this.registerForm = this.formBuilder.group({
        username:        ['', Validators.required],
        email:           ['', [Validators.required, Validators.email]],
        password:        ['', [Validators.required, Validators.minLength(6)]],
        confirmpassword: ['', [Validators.required]]
    }, {
        validator: MustMatch('password', 'confirmpassword')
    });
}

And this is the object which I send to the APi at the moment:

this.userService.registerUser(JSON.stringify(this.registerForm.getRawValue()))

2 Answers

You can delete the property on that object. First make a copy of the object to be safe.

const formCopy = Object.assign({}, this.registerForm.getRawValue()); // copy form object
delete formCopy.confirmpassword; // delete property

this.userService.registerUser(JSON.stringify(formCopy));
like image 68
charith.arumapperuma Avatar answered Sep 18 '25 19:09

charith.arumapperuma


I don't see the need to delete the form control. You can just delete the property from the object you get from the form. Also I see no need to use getRawValue(), since you have no disabled fields. So on submit I suggest:

onSubmit() {
  delete this.registerForm.value.confirmpassword;
  // ...
}

or you can pass the value of the form in the submit already:

(ngSubmit)="onSubmit(registerForm.value)"

and function:

onSubmit(values) {
  delete values.confirmpassword;
  // ...
}

and if you are doing a http-request, you don't need to stringify the value, just pass it as an object.

like image 24
AT82 Avatar answered Sep 18 '25 18:09

AT82