我正在尝试学习 Angular 4。边做边学。
我想要做的是,
1. 从服务器以 json 形式获取数据。[完成]
2. 将其填充到表单中。[有一些问题]
3. 让用户对这些数据进行更改 [完成]
4. 将新数据作为 json 发送到服务器。[问题:无法从表单中获取数据]
我面临的问题是,当我尝试提交表单时,我没有从表单中获取该数据。任何帮助表示赞赏。
我的模板文件
<div *ngIf="!name; else forminfo">
<form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)">
<div class="form-container">
<h1>Enter Details</h1>
<div class="row columns" *ngFor="let item of data;let i=index;" >
<div formArrayName="add">
<label>ID
<input type="text" formControlName="id" value="{{item.id}}">
</label>
<label>Deposit
<input type="text" formControlName="deposit" value="{{item.deposit}}">
</label>
<label>Year
<input type="text" formControlName="year" value="{{item.year}}">
</label>
<label>Maturity
<input type="text" formControlName="maturity" value="{{item.maturity}}">
</label>
</div>
</div>
<!-- [disabled]="!rForm.valid" -->
<input type="submit" class="button expanded" value="Submit Form" >
</div>
</form>
</div>
<ng-template #forminfo>
<div class="form-container">
<div class="row columns">
<h1>{{ name }}</h1>
<p>{{ description }}</p>
</div>
</div>
</ng-template>
组件文件:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {Http,Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
rForm: FormGroup;
data:any;
constructor(private fb: FormBuilder,private http: Http) {
this.rForm = fb.group({
add: this.fb.array([
this.fb.group({
id: [''],
deposit: [''],
year: [''],
maturity: [''],
})
]),
});
}
ngOnInit() {
this.http.get('http://svcsociety.com/json/yojna.txt').map((res: Response) =>
res.json()).subscribe(res => {
this.data = res;
//console.log(JSON.stringify(this.data));
});
}
addPost(post) {
alert(JSON.stringify(post));
}
}
这是 JSON 的样子
[
{"id":"1", "deposit": "Rs 50,000","year":"18","maturity":"Rs 4,00,000"},
{"id":"2", "deposit": "Rs 1,00,000","year":"18","maturity":"Rs 8,00,000"},
{"id":"3", "deposit": "Rs 1,50,000","year":"18","maturity":"Rs 12,00,000"},
{"id":"4", "deposit": "Rs 2,00,000","year":"18","maturity":"Rs 16,00,000"},
{"id":"5", "deposit": "Rs 250000","year":"18","maturity":"Rs 20,00,000"},
{"id":"6", "deposit": "Rs 300000","year":"18","maturity":"Rs 24,00,000"}
]