Angular Reactive Forms 的绑定问题

Angular Binding problem with Reactive Forms

下面是HTML组件

<div fxLayout="row" fxLayoutAlign="center center">
<mat-card fxFlex="30">
    <mat-card-content>
        <mat-card-title>
            <h2>Employee Details Form</h2>
        </mat-card-title>
        <form class="login-form"  [formGroup]="empForm" (ngSubmit)="onSubmit()">
            <div fxLayout="column">
                <p>
                    <mat-form-field class="item">
                        <input matInput type="text" placeholder="First Name" value={{firstName}} formControlName="fname"> 
                    </mat-form-field>
                </p>
                <p>
                    <mat-form-field class="item">
                        <input matInput type="text" placeholder="Last Name" value={{lastName}} formControlName="lname">
                    </mat-form-field>
                </p>
                <p>
                    <mat-form-field class="item">
                        <input matInput type="text" placeholder="Email ID" value={{emailId}} formControlName="email">
                    </mat-form-field>
                </p>
                <button mat-raised-button color="primary" type="submit">
                    <mat-icon>mic</mat-icon>
                    Submit
                </button>
            </div>
        </form>
    </mat-card-content>
</mat-card>

我需要绑定我已经从 angular http get 方法获取的表单字段。

ts 组件

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { EmployeeService } from '../service/employee/employee.service';
import { FormGroup, FormBuilder } from '@angular/forms';

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

  public id: number;
  public empForm: FormGroup;
  public firstName: string;
  public lastName: string;
  public emailId: string;

  constructor(private activateRoute: ActivatedRoute, private employeeService: EmployeeService, private formBuilder: FormBuilder) { }

  ngOnInit(): void {

    this.empForm = this.formBuilder.group({
      fname: [''],
      lname: [''],
      email: ['']
    });

    this.id = this.activateRoute.snapshot.params['id'];

    this.employeeService.getEmployeeById(this.id).subscribe(
      response => {
        this.firstName = response.firstName;
        this.lastName = response.lastName;
        this.emailId = response.emailId;
      });    
  }

  onSubmit() {
    console.log("From EMP")
    console.log(this.empForm.value);
  }
}

当我在控制台中打印值时,我得到空的表单值,但是当我编辑表单字段并提交时,我得到正确的值。我担心的是我应该在不更新表单字段的情况下获取值。

您已使用 value 属性设置值。相反,您可以直接将值设置到您的表单。检查这个:

this.employeeService.getEmployeeById(this.id).subscribe(
      response => {
        this.firstName = response.firstName;
        this.lastName = response.lastName;
        this.emailId = response.emailId;

        this.empForm.patchValue({
           fname: this.firstName,
           lname: this.lastName,
           email: this.emailId
        });
});

像这样,您将获得反应形式的双向绑定。 并从输入标签中删除 value 属性。

尝试如下操作:

<div fxLayout="row" fxLayoutAlign="center center">
    <mat-card fxFlex="30">
        <mat-card-content>
            <mat-card-title>
                <h2>Employee Details Form</h2>
            </mat-card-title>
            <form class="login-form"  [formGroup]="empForm" (ngSubmit)="onSubmit()">
                <div fxLayout="column">
                    <p>
                        <mat-form-field class="item">
                            <input matInput type="text" placeholder="First Name" formControlName="fname"> 
                        </mat-form-field>
                    </p>
                    <p>
                        <mat-form-field class="item">
                            <input matInput type="text" placeholder="Last Name"  formControlName="lname">
                        </mat-form-field>
                    </p>
                    <p>
                        <mat-form-field class="item">
                            <input matInput type="text" placeholder="Email ID" formControlName="email">
                        </mat-form-field>
                    </p>
                    <button mat-raised-button color="primary" type="submit">
                        <mat-icon>mic</mat-icon>
                        Submit
                    </button>
                </div>
            </form>
        </mat-card-content>
    </mat-card>

以及您的 .ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { EmployeeService } from '../service/employee/employee.service';
import { FormGroup, FormBuilder } from '@angular/forms';

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

  id: number;
  empForm: FormGroup;
  constructor(private activateRoute: ActivatedRoute, private employeeService: EmployeeService, private formBuilder: FormBuilder) { }

  ngOnInit(): void {

    this.empForm = this.formBuilder.group({
      fname: [''],
      lname: [''],
      email: ['']
    });

    this.id = this.activateRoute.snapshot.params['id'];

    this.employeeService.getEmployeeById(this.id).subscribe(
      response => {
        console.log(response);
        this.empForm.setValue(response);
      });    
  }

  onSubmit() {
    console.log("From EMP")
    console.log(this.empForm.value);
  }
}

尽力确保从 api 返回的对象与声明的 empForm FormGroup 中的所有属性和外壳相匹配。

这可能还会派上用场: https://www.positronx.io/angular-8-reactive-forms-validation-with-angular-material-8/