Javascript 如何在Angular 4中设置表单中的值?
我有数据要填充到表单中。我在第六章中使用了反应形式 演示应用程序 我有一个项目列表,其中有Javascript 如何在Angular 4中设置表单中的值?,javascript,angular,ngrx,ngrx-store,Javascript,Angular,Ngrx,Ngrx Store,我有数据要填充到表单中。我在第六章中使用了反应形式 演示应用程序 我有一个项目列表,其中有编辑按钮。单击编辑按钮,我将显示编辑组件 我想填充或设置输入字段中的所有值。我有一个obj中的数据,现在我想在表单中填充它 这是我的密码 在编辑组件时 ngOnInit(){ this.product$=this.store.pipe(选择(fromProduct.getSelectedProduct)) //.订阅((res)=>{ //console.log('ssss'); //console.lo
编辑
按钮。单击编辑
按钮,我将显示编辑组件
我想填充或设置输入字段中的所有值。我有一个obj中的数据,现在我想在表单中填充它
这是我的密码
在编辑组件时
ngOnInit(){
this.product$=this.store.pipe(选择(fromProduct.getSelectedProduct))
//.订阅((res)=>{
//console.log('ssss');
//console.log(res)
// },()=>{
//console.log('dddd')
// })
}
编辑按钮单击
editProduct(产品:产品,项目){
const editProduct:EditProductInterface={
产品:产品,,
selectedIndex:项目
}
this.store.dispatch(new-productActions.EditProduct(EditProduct));
this.router.navigate(['edit'])
}
您可以这样做:
<input type="text" name="name" [(ngModel)]="product.name"
required ngModel #name="ngModel">
或者这个:
<input type="text" name="name" value="{{product.name}}"
required ngModel #name="ngModel">
使用
patchValue
设置formControlValue
this.store.pipe(select(fromProduct.getSelectedProduct))
.subscribe((res)=>{
console.log('ssss'+res.productName)
this.productForm.patchValue({
productName: res.productName,
starRating: res.starRating,
productCode: res.productCode,
description: res.description,
id: res.id
});
},()=>{
console.log('dddd')
})
如果您只需要更新某些字段,请使用
patchValue
。如果您计划更新所有字段,您也可以按照以下建议使用setValue
this.productForm.patchValue({
productName: res.productName,
id: res.id
});
this.productForm.setValue({
productName: res.productName,
id: res.id,
starRating: res.starRating,
productCode: res.productCode,
description: res.description,
});
在angular中,有两种方法,setValue和patchValue使用这两种方法可以在窗体控件中设置值。 当您需要使用数据填充所有表单控件时,请使用setValue方法;当您需要仅使用数据填充特定表单控件时,请使用patchValue方法。 下面是代码示例,希望对您有所帮助 userForm:FormGroup强> **//当您需要在表单的所有控件中填充数据时,请使用下面的代码示例
this.userForm.setValue({
firstName:'test first name',
lastName:'test last name',
email:'test@test.test'
});
**//当您只需要在特定表单控件中填写数据时,请使用下面的代码示例
this.userForm.patchValue({
firstName:'test first name',
lastName:'test last name'
});
在上述两种方法中,我使用了firstName、lastName和email属性,这些属性名称需要与HTML标记中给定的formControlName名称相同
setValue和patchValue方法的官方文档可用。请使用
patchValue
this.store.pipe(select(fromProduct.getSelectedProduct)).subscribe((res) => {
this.productForm.patchValue(res);
})
downvoter请告诉我这个问题中的错误是什么` this.product$=this.store.pipe(select(fromProduct.getSelectedProduct))`而不是
subscribe
当我使用async
管道时,有没有其他方式需要订阅以访问数据?我不需要取消订阅这就是我说的原因,当你退出组件时,我会为你这么做。但是您的组件比通常情况下要保留更长的时间,那么您可以取消订阅。