form.valueChanges doesn't emit values for disabled controls

僤鯓⒐⒋嵵緔 提交于 2020-04-06 06:39:25

问题


I have an Angular Reactive form. I subscribe to its value changes and will emit changes to parent component. Some of the controls might get disabled by the user. The problem is that values from disabled controls are missing when form valueChanges are emitted. I've set a basic example.

When the checkbox is checked and the email input is disabled, there is no form control value logged. But I'd like to get ALL form values.


回答1:


Use the FormGroup's getRawValue() to include control values regardless of enable/disable state.

More information in the API documentation

this.myForm.valueChanges.subscribe(() => {
    this.formValues =  JSON.stringify(this.myForm.getRawValue());
});

Here is the forked example




回答2:


The value from a disable input is ignored (try to submit a form with a disabled input: it won't be posted).

You can change it to 'readonly'

<input formControlName="email" [readonly]="cb.checked">
<input #cb type="checkbox" formControlName="toggleEmail">

Updated example.



来源:https://stackoverflow.com/questions/47992910/form-valuechanges-doesnt-emit-values-for-disabled-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!