我有一個表格填寫不,創建使用嵌套,即顯示了一個電話號碼和一個選擇的輸入選擇的電話號碼的類型。最初,我有一套我正在嘗試賦予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, [] ]
});
}
}