我有一个表格填写不,创建使用嵌套,即显示了一个电话号码和一个选择的输入选择的电话号码的类型。最初,我有一套我正在尝试赋予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
- 代码块 -
- 电话-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, [] ]
});
}
}