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

how to set value in form in Angular 4?

我有要填充到表单中的数据。我在 Angular 6.

中使用反应形式

演示应用程序

我有一个项目列表,其中有 edit 按钮。点击 edit 按钮我显示 edit component

我想填充或设置输入字段中的所有值。我现在在 obj 中有数据,我想在 form

中填充它

这是我的代码 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')
  //       })
}

点击编辑按钮

editProduct(product: Product, item) {
  const editProduct: EditProductInterface = {
    product: product,
    selectedIndex: item
  }
  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')
        })

Demo

如果您只需要更新某些字段,请使用 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中有两种方法,setValuepatchValue使用这两种方法你可以在你的窗体的控件。 当您需要用数据填充所有表单控件时,请使用 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'
});

在以上两种方法中,我使用了名字,姓氏和电子邮件属性,这些属性名称需要与您的formControlName相同HTML 标记中给出的名称。

setValue 和 patchValue 方法官方文档可用here

为此使用 patchValue

this.store.pipe(select(fromProduct.getSelectedProduct)).subscribe((res) => {
    this.productForm.patchValue(res);
})