Change ngForm field value

Michalis picture Michalis · Apr 22, 2017 · Viewed 12.2k times · Source

When i submit my form, i have this function

login(form: NgForm)

If I try the following

console.log(form.value.password); // this works perfect.

but this doesn't work

form.value.password = ''

After failed login i want to reset the password field.

Answer

Jorawar Singh picture Jorawar Singh · Apr 23, 2017

but this doesn't work

form.value.password = ''

Because form.value returns you value of the form and it is an read only property part of AbstractControl

From angular2 source code

/**
 * The value of the control.
 */
readonly value: any;

You can use reset for your purpose.

/** * Resets the control. Abstract method (implemented in sub-classes). */

abstract reset(value?: any, options?: Object): void;

Usage of setValue or patchValue.

this.yourForm.controls['password'].setValue(password)

Or you can assign value to whole form

this.yourForm.setValue(data);

When using setValue on whole form then you have ro provide every control otherwise it throw error like property missing paychValue in other hand can handle if you sending only on element.