【问题标题】:Angular Binding problem with Reactive Forms反应式表单的角度绑定问题
【发布时间】:2020-05-08 14:20:22
【问题描述】:

下面是 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);
  }
}

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

【问题讨论】:

    标签: angular angular-material angular-ui-router angular-reactive-forms


    【解决方案1】:

    您已使用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 属性。

    【讨论】:

    • 感谢 Tushar,在采纳您的建议后已解决此问题。
    【解决方案2】:

    试试下面的方法:

    <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/

    【讨论】:

    • 感谢您的建议,但这仍然无法正常工作同样也可以进行 2 路绑定。
    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2022-01-02
    • 2019-02-04
    相关资源
    最近更新 更多