具有反应形式的角装订问题

问题描述 投票:0回答:1

下面是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>

我需要绑定我已经从有角度的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
1个回答
0
投票
您已使用value属性设置该值。相反,您可以将值直接设置为表单。检查此:

0
投票
尝试以下操作:
© www.soinside.com 2019 - 2024. All rights reserved.