在Angular中,我们可以使用FormControl来处理表单数据。有时候,我们需要在表单中使用下拉列表、多选框等控件来处理一些支持数据(如国家、城市等)。那么在处理支持数据时,我们需要如何使用FromControls呢?
首先,我们要创建一个FormControl来处理表单数据。其次,我们需要从服务端获取支持数据,然后将其绑定到下拉列表或多选框等控件上。在完成选择后,我们可以将所选的值存储到FormControl中。
下面是一个代码示例,代码中演示了如何将Angular FromControls和支持数据结合使用:
在组件中:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { DataService } from './data.service';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
form: FormGroup;
countries = [];
constructor(private fb: FormBuilder, private dataService: DataService) { }
ngOnInit() {
this.form = this.fb.group({
country: new FormControl('')
});
this.dataService.getCountries().subscribe(data => {
this.countries = data;
});
}
onSubmit() {
console.log(this.form.value); // outputs { country: 'USA'}
}
}
在服务中:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class DataService {
private apiUrl = 'https://restcountries.eu/rest/v2/all';
constructor(private http: Http) { }
getCountries(): Observable {
return this.http.get(this.apiUrl)
.map(response => response.json())
}
}
在模板中: