Angular 6 patchValue 未设置......有时

Eva*_*alo 1 forms angular6

我有一个如下所示的基本形式。我调用一个 API 来获取用户的个人信息,我想用适当的值填充表单字段。我一直在尝试使用,patchValue但我无法让它工作。

    <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> -->
Run Code Online (Sandbox Code Playgroud)

这是我的 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();

  }

}
Run Code Online (Sandbox Code Playgroud)

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

任何帮助,将不胜感激。

谢谢,

Ani*_*had 11

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

正确的语法是,

this.firstFormGroup.patchValue({[item]: value});
Run Code Online (Sandbox Code Playgroud)

使用 [item] 代替 item

[item] 表示添加到 formGroup 的动态键