[英]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.