>

아래 그림과 같은 기본 형식이 있습니다. 사용자의 개인 정보를 얻기 위해 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> -->

여기 내 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 로 하드 코딩하면 필드가 설정됩니다.

도움을 주시면 감사하겠습니다.

감사합니다,


  • 답변 # 1

    귀하의 경우 patchValue 구문이 잘못되었습니다.

    올바른 구문은

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

    항목 대신 [item] 사용

    [item] formGroup에 추가 된 동적 키를 의미합니다

  • 이전 ruby - 레일에 이메일을 보내는 버튼
  • 다음 node.js - localhost에서 Botbuilder 봇의 응답이 없지만 Azure에서 작동