使用角度和火基编辑/更新反应式表单



我正在尝试通过elementId从另一个视图编辑/更新表单。

employee-list.comonent.ts(view 2):

 onEdit(empId:string){
this._router.navigate(['/RegisterEmployee',empId]);
//this.service.formData=Object.assign({},emp);
 }

单击它会导航到另一个视图,其中包含所选元素的 ID,但如何从所选元素的数据库中填充表单数据并更新 Firebase 数据库上的编辑数据

employee.component.ts(view 1)-Reactive-Form

 ngOnInit() {
//this.resetForm();
this.form = this.formBuilder.group({
  fullName:new FormControl('',[Validators.required,Validators.pattern('[a-zA-Z][a-zA-Z ]+')]),
  designation: new FormControl('',[Validators.required,Validators.pattern('[a-zA-Z][a-zA-Z ]+')]),
  Email: new FormControl('',[Validators.required, Validators.email]),
  mobile: new FormControl('',[Validators.required, Validators.pattern('[0-9]*'),Validators.minLength(10),Validators.maxLength(10)])
});
 }
 /* submit the data to be added into database having 'employees' as the data 
 collection array*/
 onSubmit():void{
console.log(this.form.value);
this.router.navigateByUrl('/EmployeeList');
let data = Object.assign({},this.form.value);
if(this.form.value.id == null)
this.firestore.collection('employees').add(data);
else
this.firestore.doc('employees/'+this.form.value.id).update(data);
//this.resetForm(this.form);
this.toastr.success('Submitted successfully','Employee Register');
 }

我的服务如下:员工服务.ts

import { Injectable } from '@angular/core';
import { Employee } from './employee.model';
import { AngularFirestore } from '@angular/fire/firestore';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
formData : Employee;
constructor(private firestore:AngularFirestore) { }
/*Function to get added employees list from firebase database*/
getEmployees(){
let listOfEmployees = 
 this.firestore.collection('employees').snapshotChanges();
 return listOfEmployees;
  }
   }

我的表单界面:员工模型

export class Employee {
id : string;
fullName: string;
Email: string;
mobile: string;
designation :string;
}

请帮助解决这个问题(Angular 新手和我使用 Firebase 的第一个项目)。

这是用于工作应用程序 https://github.com/HusnaKhanam/MyApplication 的 Git 存储库

如果我理解正确,以下是用数据填充表单的基本步骤:

在员工组件中:

1) 从 url 参数中读取 id,如下所示:

  ngOnInit() {
    const param = this.route.snapshot.paramMap.get('id');
    if (param) {
      const id = +param;
      this.getProduct(id);
    }
  }

(注意:这是我的代码,您需要根据您的特定方案对其进行修改。

2) 从服务中获取类似于以下内容的数据:

  getProduct(id: number): void {
    this.productService.getProduct(id)
      .subscribe(
        (product: Product) => this.displayProduct(product),
        (error: any) => this.errorMessage = <any>error
      );
  }

3) 使用类似于以下内容的代码更新表单上的数据:

  displayProduct(product: Product): void {
    this.product = product;
    // Update the data on the form
    this.productForm.patchValue({
      productName: this.product.productName,
      productCode: this.product.productCode,
      starRating: this.product.starRating,
      description: this.product.description
    });
  }

最新更新