Angular 6 patchValue未设置..有时 [英] Angular 6 patchValue Not Setting..sometimes

查看:45
本文介绍了Angular 6 patchValue未设置..有时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的基本表格.我调用一个API来获取用户的个人信息,并且我想用适当的值填充表单字段.我一直在尝试使用patchValue,但是我无法使用它.

I have a basic form shown below. I make a call to an API to grab the user's personal info and I want to fill the form fields with the appropriate values. I have been trying to use patchValue but I cannot get it to work.

    <form (ngSubmit)="onSubmit" class="example-form" [formGroup]="firstFormGroup" #registerForm="ngForm">
<mat-form-field class="example-full-width">
  <input matInput placeholder="Company" formControlName="company" required autofocus>
  <mat-error *ngIf="firstFormGroup.get('company').hasError('required')">
    Company name is
    <strong>required</strong>
  </mat-error>
</mat-form-field>

<table class="example-full-width" cellspacing="0">
  <tr>
    <td>
      <mat-form-field class="example-full-width">
        <input matInput placeholder="First name" formControlName="first_name" required>
        <mat-error *ngIf="firstFormGroup.get('first_name').hasError('required')">
          First name is
          <strong>required</strong>
        </mat-error>
      </mat-form-field>
    </td>
    <td>
      <mat-form-field class="example-full-width">
        <input matInput placeholder="Last Name" formControlName="last_name" required>
        <mat-error *ngIf="firstFormGroup.get('last_name').hasError('required')">
          Last name is
          <strong>required</strong>
        </mat-error>
      </mat-form-field>
    </td>
  </tr>
  <tr>
    <td>
      <mat-form-field class="example-full-width">
        <input matInput placeholder="Email" formControlName="email" required>
        <mat-error *ngIf="firstFormGroup.get('email').hasError('email') && !email.hasError('required')">
          Please enter a valid email address
        </mat-error>
        <mat-error *ngIf="firstFormGroup.get('email').hasError('required')">
          Email is
          <strong>required</strong>
        </mat-error>
      </mat-form-field>
    </td>
  </tr>
</table>

<p>
  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Address" formControlName="address" required></textarea>
  </mat-form-field>
  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Address 2"></textarea>
  </mat-form-field>
</p>

<table class="example-full-width" cellspacing="0">
  <tr>
    <td>
      <mat-form-field class="example-full-width">
        <input matInput placeholder="City" formControlName="city" required>
      </mat-form-field>
    </td>
    <td>
      <mat-form-field class="example-full-width">
        <mat-select placeholder="State" formControlName="state" required>
          <mat-option>None</mat-option>
          <mat-option *ngFor="let state of states" [value]="state">{{state}}</mat-option>
        </mat-select>
      </mat-form-field>
    </td>
    <td>
      <mat-form-field class="example-full-width">
        <input matInput #postalCode maxlength="5" placeholder="Postal Code" value="" formControlName="zip" required>
        <mat-hint align="end">{{postalCode.value.length}} / 5</mat-hint>
      </mat-form-field>
    </td>
  </tr>
</table>
<button type="submit" class="register" mat-button (click)="check()"
  color="primary">Save</button>
      <!-- <button type="submit" [disabled]="!registerForm.form.valid" class="register" mat-button (click)="check()" color="primary">Save</button> -->

这是我的ts文件:

import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login.service';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';

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

  firstFormGroup: FormGroup;
  profileInfo: Object[];


  constructor(private _formBuilder: FormBuilder, private _auth: LoginService) { }
  getInfo() {
    let value;
    this._auth.profile({'username': 'evanlalo'})
    .subscribe(res => {
        for (const item in res) {
          if (this.firstFormGroup.value.hasOwnProperty(item)) {
            value = res[item];
            console.log(value);
            this.firstFormGroup.patchValue({ item: value });
            console.log(item, res[item]);
          }
        }

    });
 }




  ngOnInit() {


    this.firstFormGroup = this._formBuilder.group({
      company: new FormControl('', Validators.required),
      first_name: new FormControl('', Validators.required),
      last_name: new FormControl('', Validators.required),
      address: new FormControl('', Validators.required),
      city: new FormControl('', Validators.required),
      state: new FormControl('', Validators.required),
      zip: new FormControl('', Validators.required),
      email: new FormControl('', [
        Validators.required,
        Validators.email,
      ])
    });

    this.getInfo();

  }

}

所有键都与表单字段名称匹配,但是如果使用item变量,它将不起作用.奇怪的是,如果我对字段名称IE company进行硬编码,则将设置该字段.

All of the keys match the form field names but it will not work if I use the item variable. The weird thing is that if I hard code the field name IE company, the field will be set.

任何帮助将不胜感激.

谢谢

推荐答案

在您的情况下,patchValue语法错误.

In your case patchValue syntax is wrong.

正确的语法是

this.firstFormGroup.patchValue({[item]: value});

使用[item]代替项目

use [item] instead of item

[item]这意味着将动态键添加到formGroup

[item] it means dynamic keys added to formGroup

这篇关于Angular 6 patchValue未设置..有时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆