【发布时间】:2017-02-20 23:10:13
【问题描述】:
我有一个使用嵌套创建的表单,它显示了一个带有电话号码的输入和一个选择电话号码类型的选项。最初,我有一组值,我试图在创建 formGroup 时分配它们。但是,虽然选择框获取其选项,但它不会选择预定义值。输入框也不接收它的预定义值。
在app.component.ts:57 中,我正在获取我的预定义值数组并单独解析它们并调用addPhoneForm 方法。
addPhoneForm 方法也使用了initPhoneForm 方法。这些一起创建了可以在app.component.html 的第 33 行看到的电话表单。
我认为它没有被填写的原因是因为我还在我的 PhoneDetailComponent 构造函数中执行以下代码:
this.phoneForm = this.formBuilder.group({
phoneNumber: new FormControl(),
phoneType: new FormControl()
})
但如果没有那段代码,我会收到一条错误消息,指出 formGroup 需要一个 FormGroup。
这是我正在做的事情的 plnkr。 http://plnkr.co/edit/qv1BX7WtpYhw5B92SuoC?p=preview
-- 代码块--
-- phone-detail.component.ts
export class PhoneDetailComponent {
phoneTypes: EnumProperty[] = [];
phoneForm: FormGroup;
@Input('group')
@Output() rawChange: EventEmitter<string> = new EventEmitter<string>();
constructor(private phoneTypeService: PhoneTypeService,
private formBuilder: FormBuilder) {
this.getPhoneTypes();
this.phoneForm = this.formBuilder.group({
phoneNumber: new FormControl(),
phoneType: new FormControl()
})
}
private getPhoneTypes() {
this.phoneTypeService.get()
.then(phoneTypes => {
this.phoneTypes = phoneTypes;
})
}
}
-- app.component.html:31-36
<div formArrayName="phones">
<div *ngFor="let phone of updateProfileForm.controls.phones.controls; let i=index">
<phone [group]="updateProfileForm.controls.phones.controls[i]"></phone>
</div>
</div>
<a (click)="addPhoneForm()">+ Add another phone number</a>
-- app.component.ts(仅相关部分)
export class AppComponent {
private version: any;
updateProfileForm: FormGroup;
phoneNumbers: PhoneModel[] = [
{ phoneNumber: "843-555-5849", type: "sms" },
{ phoneNumber: "756-555-7643", type: "home"},
{ phoneNumber: "395-555-9324", type: "tty" },
{ phoneNumber: "621-555-2690", type: "sms" }
]
private phoneValidator = Validators.compose([
Validators.minLength(7),
Validators.maxLength(16),
Validators.pattern(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/) ]);
constructor(http: Http,
private formBuilder: FormBuilder) {
// Display the currently used Material 2 version.
this.version = http
.get('https://api.github.com/repos/angular/material2-builds/commits/HEAD')
.map(res => res.json())
this.updateProfileForm = this.formBuilder.group({
personNames: ['', []],
phones: this.formBuilder.array([])
});
console.log("Loading phones");
this.phoneNumbers.forEach(p => this.addPhoneForm(p));
}
private addPhoneForm(p?: PhoneModel) {
if (!p) {
p.phoneNumber = "";
p.type = PHONE_TYPES[0];
}
const control = <FormArray>this.updateProfileForm.controls['phones'];
const phnCtrl = this.initPhoneForm(p);
console.log(p);
control.push(phnCtrl);
}
private initPhoneForm(phoneModel: PhoneModel) {
console.log(phoneModel);
return this.formBuilder.group({
phoneNumber: [ phoneModel.phoneNumber, this.phoneValidator ],
phoneType: [ phoneModel.type, [] ]
});
}
}
【问题讨论】:
标签: angular