首页 文章

无法在Angular Forms中使用patchValue方法

提问于
浏览
0

数据未显示在编辑页面中 . 我从API获取数据,这些数据我也可以进入service.ts文件,但是我无法在编辑页面上显示它 .

Edit.customer.ts

import { Component, OnInit } from '@angular/core';
import { CustomerService } from './customer.service';
import { Customer } from '../models/customer.model';
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { Router } from "@angular/router";
import { first } from "rxjs/operators";

@Component({
  selector: 'app-edit-customer',
  templateUrl: './edit-customer.component.html',
  styleUrls: ['./edit-customer.component.css']
})
export class EditCustomerComponent implements OnInit {

  customer: Customer;
  editForm: FormGroup;

  constructor(private formBuilder: FormBuilder, private router: Router, private _customerService: CustomerService) { }

  ngOnInit() {
    let id = localStorage.getItem("editCustomerId");
    if (!id) {
      alert("Invalid Action")
      this.router.navigate(['list']);
      return;
    }
    this.editForm = this.formBuilder.group({
      customerId: [],
      name: new FormControl('', [Validators.required]),
      email: ['', Validators.required],
      primaryPhone: ['', Validators.required],
      alternatePhone: [''],
      address1: ['', Validators.required],
      address2: ['', Validators.required],
      address3: [''],
      city: ['', Validators.required],
      state: ['', Validators.required],
      country: ['', Validators.required],
      zip: ['', Validators.required],
    });    
    this._customerService.getCustomerById(+id).subscribe(data => {
      this.editForm.patchValue(data);
      console.log(data);
    });
  }
  onSubmit() {
    this._customerService.updateCustomer(this.editForm.value)
      .pipe(first())
      .subscribe(
        data => {
          this.router.navigate(['list']);
        },
        error => {
          alert(error);
        });
  }
}

1 回答

  • 0

    您必须为PatchValue方法定义键:

    对于前者

    this.yourform.patchValue({key : "value" });
    

    您也可以使用动态执行此操作

    this.yourform.patchValue({[key] : [value]});
    

    在你的情况下:

    // This is your data from API
    var data = {
      name: "Prashant",
      email: "prashantpimpale93@gmail.com"
    }
    
    // use the patch value with dynamic keys
    Object.keys(data).forEach(key => {
      this.editForm.patchValue({ [key]: data[key] });
    })
    

    使用来自API服务的数据:

    this._customerService.getCustomerById(id).subscribe(value => {
      if (value) {
         this.data = value;
      }
    });
    
    // Then use patchValue
    Object.keys(this.data).forEach(key => {
       this.editForm.patchValue({ [key]: this.data[key] });
    })
    

    StackBlitz Example

相关问题