[英]Problem with input field in a FormGroup in ionic/angular
我對 FormGroup 有疑問。 我有一個地點描述列表,用於填寫帶有相應離子輸入字段的表格。 用戶應該能夠更新描述並提交它。 但是當我不更新字段中的值時,發送到 ts 文件的數據是空的,即使它在屏幕上顯示得很好。 你能告訴我如何解決它嗎?
這是我的 html 文件:
<ion-content padding class="form-content" [fullscreen]="true">
<ion-header collapse="condense">
<ion-toolbar>
<ion-title size="large">Debug</ion-title>
</ion-toolbar>
</ion-header>
<form [formGroup]="validations_form" (ngSubmit)="onSubmit(validations_form.value)">
<div *ngFor="let place of (places | async)">
<ion-item>
<ion-label color="primary"></ion-label>
<ion-input type="text" formControlName="desc_{{place.id}}" [value]="place.name"></ion-input>
</ion-item>
</div>
<ion-button expand="full" type="submit">Save</ion-button>
</form>
</ion-content>
這是我的ts:
import { Component} from '@angular/core';
import { Observable } from 'rxjs';
import { Validators, FormBuilder, FormGroup, FormControl, FormArray, ValidationErrors } from '@angular/forms';
import { PersonService } from '../../person.service';
import Place from '../../types';
@Component({
selector: 'app-debug',
templateUrl: './debug.page.html',
styleUrls: ['./debug.page.scss'],
})
export class DebugPage {//} implements OnInit {
places: Observable<Place[]>;
validations_form: FormGroup;
constructor(
public formBuilder: FormBuilder,
public personService: PersonService
) {
this.places = personService.getAllPlaces_full();
this.validations_form = this.formBuilder.group({
'desc_1': ['', Validators.required],
'desc_2': ['', Validators.required],
'desc_3': ['', Validators.required],
'desc_4': ['', Validators.required],
'desc_5': ['', Validators.required],
'desc_6': ['', Validators.required]});
}
onSubmit(values){
console.log(values);
for (let [key, value] of Object.entries(values)) {
if (!( value ===null))
{
console.log(`${key}: ${value}`);
}
}
}
}
這是屏幕:屏幕
這是日志:控制台中的日志
用於填充表單的 model 是: validations_form
。 這完全獨立於可觀察的位置,您必須將可觀察的用作 model,並且通過使用 RXJS,您可以輕松地從可觀察的 Z4C4AD5FCA2E7A3F74DBB1CED040Z 中讀取數據:
<ion-content padding class="form-content" [fullscreen]="true">
<ion-header collapse="condense">
<ion-toolbar>
<ion-title size="large">Debug</ion-title>
</ion-toolbar>
</ion-header>
<form [formGroup]="places | async as Places" (ngSubmit)="onSubmit()">
<div *ngFor="let place of Places">
<ion-item>
<ion-label color="primary"></ion-label>
<ion-input type="text" formControlName="desc_{{place.id}}" [value]="place.name"></ion-input>
</ion-item>
</div>
<ion-button expand="full" type="submit">Save</ion-button>
</form>
</ion-content>
TS:
onSubmit(){
places.subscribe(res => {
console.log(res);
// do something with your data
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.