Angular 6 getRawValue() 不会 return 禁用值
Angular 6 getRawValue() will not return disabled values
我有一个示例表格如下:
stuff: IStuff;
buildForm() {
this.createForm = this.form.group({
Val1: [{ value: '', disabled: true }],
Val2: [{ value: '', disabled: true }]
});
如您所见,两个值都设置为禁用。
构造函数触发 httpClient get 并填充模型:
this.exampleHttpService.getStuff()
.subscribe(stuff => this.stuff = stuff);
东西在哪里:
export interface IStuff {
Val1?: number;
Val2?: number
}
Val1 和 Val2 的绑定在 html 中完成,如下所示:
<input name="Val1" matInput formControlName="Val1" [value]="stuff?.Val1">
这太棒了,它很好地分配了值并将它们显示在屏幕上;但是,当我尝试使用
取回这些值时
this.createForm.getRawValue()
我得到两个值的“”空字符串...
有什么想法吗?
从服务取回数据后,您是否在 FormControls 上设置了值?从我看到的代码来看,您将 FormControls 初始化为空字符串,这让我猜想您可能没有设置值?
当你使用响应式表单时,输入值已经绑定到表单控件,你不需要(也不应该)绑定到输入值,因为值和表单控件不一样事物。在您的代码中,您正在初始化绑定到输入值的 'stuff',但您没有初始化表单控件值。您需要初始化表单控件值:
this.exampleHttpService.getStuff()
.subscribe((stuff) => {
this.createForm.controls['Val1'] = stuff.Val1;
this.createForm.controls['Val2'] = stuff.Val2;
});
初始化响应式表单的正确方法是:
stuff: IStuff;
buildForm() {
//Get value for stuff before initializing form
this.createForm = this.form.group({
Val1: [{ stuff.Val1: '', disabled: true }],
Val2: [{ stuff.Val2: '', disabled: true }]
});
这里还有一个值得注意的地方是获取表单的值,this.createForm.value
不会为禁用的控件提供更新的值。 this.createForm.getRawValue()
是这种情况下的选项。
我有一个示例表格如下:
stuff: IStuff;
buildForm() {
this.createForm = this.form.group({
Val1: [{ value: '', disabled: true }],
Val2: [{ value: '', disabled: true }]
});
如您所见,两个值都设置为禁用。
构造函数触发 httpClient get 并填充模型:
this.exampleHttpService.getStuff()
.subscribe(stuff => this.stuff = stuff);
东西在哪里:
export interface IStuff {
Val1?: number;
Val2?: number
}
Val1 和 Val2 的绑定在 html 中完成,如下所示:
<input name="Val1" matInput formControlName="Val1" [value]="stuff?.Val1">
这太棒了,它很好地分配了值并将它们显示在屏幕上;但是,当我尝试使用
取回这些值时this.createForm.getRawValue()
我得到两个值的“”空字符串...
有什么想法吗?
从服务取回数据后,您是否在 FormControls 上设置了值?从我看到的代码来看,您将 FormControls 初始化为空字符串,这让我猜想您可能没有设置值?
当你使用响应式表单时,输入值已经绑定到表单控件,你不需要(也不应该)绑定到输入值,因为值和表单控件不一样事物。在您的代码中,您正在初始化绑定到输入值的 'stuff',但您没有初始化表单控件值。您需要初始化表单控件值:
this.exampleHttpService.getStuff()
.subscribe((stuff) => {
this.createForm.controls['Val1'] = stuff.Val1;
this.createForm.controls['Val2'] = stuff.Val2;
});
初始化响应式表单的正确方法是:
stuff: IStuff;
buildForm() {
//Get value for stuff before initializing form
this.createForm = this.form.group({
Val1: [{ stuff.Val1: '', disabled: true }],
Val2: [{ stuff.Val2: '', disabled: true }]
});
这里还有一个值得注意的地方是获取表单的值,this.createForm.value
不会为禁用的控件提供更新的值。 this.createForm.getRawValue()
是这种情况下的选项。