我有一个如下所示的基本表格。我调用一个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
进行硬编码,则将设置该字段。
任何帮助将不胜感激。
谢谢
答案 0 :(得分:2)
在您的情况下,patchValue语法错误。
正确的语法是
this.firstFormGroup.patchValue({[item]: value});
使用[item]代替项目
[item]这意味着将动态键添加到formGroup
答案 1 :(得分:1)
如果在patchValue中未定义任何值部分,则它也不起作用。 例如在下面的示例中,如果我想修补一些列,例如id,projectName等,并且以某种方式未定义 this.project.Id 元素(未从服务填充),那么patchValue也将无法工作而不会引发任何错误。
this.projectForm.patchValue({
id:this.project.Id,
ProjectName:this.project.ProjectName,
})
答案 2 :(得分:0)
如果您使用的是Angular 9+,请阅读此内容。
在Angular文档中,使用setValue({key: value})
代替patchValue({key: value})
确实有意义,因为setValue
不会吞并错误。如果您的对象嵌套/复杂,您将被抛弃。
有两种方法可以更新模型值:
Use the setValue() method to set a new value for an individual control. The setValue() method strictly adheres to the structure of
窗体组并替换控件的整个值。
Use the patchValue() method to replace any properties defined in the object that have changed in the form model.
对setValue()方法的严格检查有助于捕获嵌套错误 以复杂的形式出现,而patchValue()在出现这些错误时会静默失败。
您也不能使用patchValue({[key]: value}); //no parenthesis