Angular Проблема привязки с реактивными формами - PullRequest
0 голосов
/ 07 мая 2020

Ниже 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 component

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);
  }
}

Когда я печатаю значения в консоли, я получаю пустые значения формы, но когда я редактирую поля формы и отправляю, я получаю правильные значения. Меня беспокоит, что я должен получать значения, даже не обновляя поля формы.

Ответы [ 2 ]

2 голосов
/ 07 мая 2020

Вы использовали атрибут 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 из входного тега.

0 голосов
/ 07 мая 2020

Попробуйте что-то вроде ниже:

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...