[英]How to iterate on a dynamic FormControl with Angular2 and FormBuilder?
[英]Angular2: how to access a formControl value on a nested formBuilder form
如何在不使用[ngModel]
情况下获取this.resFormGroup.patientName.lastname.value
的值?
在HTML <form>
标记中, name="resForm"
, [formGroup]="resFormGroup"
和#resNgForm="ngForm"
的目的是什么?
我需要模板引用变量#resNgForm
因为我有[formGroup]="resFormGroup"
吗?
这是我的组成部分:
// FormBuilder
this.resFormGroup = this.formBuilder.group({
patientName: this.formBuilder.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required]
}),
address: this.formBuilder.group({
street: [],
zip: [],
city: []
})
});
这是我的模板:
<form name="resForm" [formGroup]="resFormGroup" (ngSubmit)="onSubmit()" #resNgForm="ngForm">
<fieldset formGroupName="patientName">
<legend>Name</legend>
<label>Firstname:</label>
<input type="text" formControlName="firstname" [(ngModel)]="myFirstName">
<label>Lastname:</label>
<input type="text" ***formControlName="lastname"***>
</fieldset>
<fieldset formGroupName="address">
<legend>Address</legend>
<label>Street:</label>
<input type="text" formControlName="street">
<label>Zip:</label>
<input type="text" formControlName="zip">
<label>City:</label>
<input type="text" formControlName="city">
</fieldset>
<button type="submit" class="btn btn-primary" [disabled]="!resNgForm.valid">Submit</button>
我的提交按钮:
onSubmit() {
console.log("Submit button pressed [ngModel: " + this.myFirstName + "] [Form: " + this.resFormGroup.controls["patientName"].dirty + "]");
}
使用[ngModel]
,我可以获得名字; 我还可以访问formGroup
的patientName
的dirty
属性。
基于这个关于动态表单的教程,他们使用一种非常简单的方法来显示整个表单的值,而不需要[ngModel]。
如何获取formBuilder表单值? 答案是'this.myForm.value'。
例如:
onSubmit(model: ResCrud) {
console.log("Nested Control: " + JSON.stringify(this.resFormGroup.value));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.