如何在 Angular 4 的表单中设置值?

use*_*513 0 javascript ngrx angular ngrx-store

我有要填充到表单中的数据。我在 Angular 6 中使用反应式形式。

演示应用程序

我有其中有edit按钮的项目列表。单击edit我正在显示的按钮edit component

我想填充或设置输入字段中的所有值。我现在在 obj 中有数据我想以表格形式填充它

这是我的代码 https://stackblitz.com/edit/angular-pkf4wa?file=src%2Fapp%2Fedit%2Fedit.component.ts

在编辑组件上

ngOnInit() {
  this.product$ = this.store.pipe(select(fromProduct.getSelectedProduct))
  //       .subscribe((res)=>{
  //    console.log('ssssss');
  // console.log(res)
  //       },()=>{
  //         console.log('dddd')
  //       })
}
Run Code Online (Sandbox Code Playgroud)

编辑按钮点击

editProduct(product: Product, item) {
  const editProduct: EditProductInterface = {
    product: product,
    selectedIndex: item
  }
  this.store.dispatch(new productActions.EditProduct(editProduct));
  this.router.navigate(['edit'])
}
Run Code Online (Sandbox Code Playgroud)

小智 6

在 angular 中,有两种方法setValuepatchValue使用这两种方法您可以在表单的控件中设置值。当您需要使用数据填充所有表单控件时,请使用setValue方法,当您需要仅使用数据填充特定表单控件时,请使用patchValue方法。下面是代码示例,希望对您有所帮助。

用户表单:表单组;

**//当您需要在表单的所有控件中填写数据时使用下面的代码示例。

this.userForm.setValue({
    firstName:'test first name',
    lastName:'test last name',
    email:'test@test.test'
});
Run Code Online (Sandbox Code Playgroud)

**//当您只需要在特定的表单控件中填写数据时使用下面的代码示例

this.userForm.patchValue({
    firstName:'test first name',
    lastName:'test last name'
});
Run Code Online (Sandbox Code Playgroud)

在上述两种方法中,我使用了 firstName、lastName 和 email 属性,这些属性名称需要与HTML 标记中给出的formControlName名称相同。

setValue 和 patchValue 方法的官方文档可在此处获得