Search code examples
javascriptangularngrxngrx-store

how to set value in form in Angular 4?


I have data I want to populate in a form. I am using reactive form in Angular 6.

Demo Application

I have list of items in which there is edit button .On click of edit button I am showing edit component

I want to populate or set all values in input field. I have data in an obj now I want to populate that in form

here is my code https://stackblitz.com/edit/angular-pkf4wa?file=src%2Fapp%2Fedit%2Fedit.component.ts

on Edit component

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

Edit button click

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

Solution

  • use the patchValue to set the 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