【发布时间】:2019-07-06 00:23:04
【问题描述】:
我正在使用响应式表单,其中我想要双向数据绑定,因此我使用“值”属性来初始化表单组的默认值。因为表单组在 ngFor 循环中,但是当我尝试获取表单时,我只获得编辑的值并且无法获得默认值,我似乎“value”属性没有初始化表单控件,它只显示在 DOM 中。
TS:
userForm: FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit(){
this.userForm = this.fb.group({
userName: [''],
fullName: [''],
email: [''],
});
}
OnUpdateClick() {
console.log(this.userForm.get('userName').value);
console.log(this.userForm.get('fullName').value);
console.log(this.userForm.get('email').value);
}
HTML:
<div *ngFor="let agent of agents">
<form [formGroup]="userForm" >
<mat-form-field >
<mat-label>Name</mat-label>
<input matInput id="Name" name="name" value="
{{agent.username}}" formControlName="userName">
</mat-form-field>
<mat-form-field >
<mat-label>Name</mat-label>
<input matInput id="FName" name="Fname" value="
{{agent.fullName}}" formControlName="fullName">
</mat-form-field>
<mat-form-field >
<mat-label>Name</mat-label>
<input matInput id="email" name="email" value="
{{agent.email}}" formControlName="email">
</mat-form-field>
<button (click)="OnUpdateClick()"> SAVE </button>
</div>
当我尝试在“OnUpdateClick”函数中获取表单字段时,我只得到那些我弄脏的值,未触及的控件也应该返回它们的默认值
【问题讨论】:
-
不,@HameedSyed,他有一个反应形式,他必须 REMOVE value="{{...}}
-
@Eliseo 你能告诉我在这种情况下实现双向绑定的最简单方法吗
-
我回答了
标签: angular typescript angular-reactive-forms