我有以下 Angular 7 表单:
ngOnInit() {
this.organizationId = 1; // Used for testing
this.form = this.formBuilder.group({
name: [''],
organizationId: [{ value: this.organizationId, disabled: this.enableOrganizationChange }],
start: ['']
});
}
在 HTML 中,我为 OrganizationId
使用了 Select
。它按预期被禁用。
但是在提交时值为 null
而不是 1:
onSubmit() {
if (this.form.valid) {
this.submitting = true;
console.log(this.form.value.organizationId);
let request: Request = {
name: this.form.value.name,
organizationId: this.form.value.organizationId.value,
start: this.form.value.start
};
}
}
为什么记录的值是 null
而不是 1
?
我使用 disabled 只是为了避免用户更改值。
但我仍然需要提交时的值...
最佳答案
正如您所注意到的,Angular 会忽略表单对象中禁用的表单控件。
这可以通过使用 getRawValue() 轻松解决,它包括所有表单控件,无论是否禁用。因此,例如在您的提交中,您像这样传递表单(而不是表单值):
(ngSubmit)="onSubmit(form)"
Then you can use getRawValue:
onSubmit() {
console.log(form.getRawValue())
}
请注意,所有这些都是使用 NgForms 而不是 ReactiveForms 发生的。
您可以通过添加 getRawValue()
相应地更改 For ReactiveForms,例如:console.log(this.form.organizationId.getRawValue());
关于angular - 表单控件值在禁用时变为空 OnSubmit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497735/