我在angular 4中创建了一个formGroup,其中user&组织存储在对象中。现在我想使用这两个对象填充我的表单组。 在我的判断中,我做了以下几点:
createForm(user: any) {
this.userForm = this.fb.group({
name: user.profileData.name,
email: user.profileData.email,
phone: user.profileData.mobileNumber,
orgForm: this.fb.group({
name: [ user.organisation.name , [Validators.required]]
})
});
}
在我看来,我正在做这样的事情:
<form [formGroup]="userForm" class="user-form" (ngSubmit)="onSubmit()" novalidate>
<div fxLayout="row">
<div fxLayout="column" fxFlex="50%">
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="User Name" formControlName="name">
</md-input-container>
</div>
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="User Email" formControlName="email">
</md-input-container>
</div>
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="User Phone" formControlName="phone">
</md-input-container>
</div>
<div class="form-group">
<button md-raised-button type="submit" [disabled]="userForm.pristine">Save</button>
</div>
</div>
<div fxLayout="column" fxFlex="50%" formGroupName="orgForm">
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="Organization Name" formControlName="name">
</md-input-container>
</div>
</div>
</div>
</form>
但我收到以下错误:
formGroup需要一个FormGroup实例,请在
中传递一个
任何输入?
答案 0 :(得分:10)
如果您未在组件的构造函数中创建表单,则第一次呈现视图时userForm可能未定义,这就是您获取该错误的原因。 将表单标记封装成以下内容:
<div *ngIf='userForm'>
</div>
因此只有在设置了模型后才会生成表单视图。
答案 1 :(得分:0)
使用您的代码和HTML,它可以在此链接中使用而无需更改org。 LINK
只需复制下面的代码并将其粘贴在 dyniamic-form.component.ts
中import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';
@Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
providers: [ QuestionControlService ]
})
export class DynamicFormComponent implements OnInit {
@Input() questions: QuestionBase<any>[] = [];
form: FormGroup;
payLoad = '';
constructor(private qcs: QuestionControlService, private fb: FormBuilder) { }
userForm;
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions);
this.userform = this.createForm({profileData:{
name: 'h',
email: 'l',
mobileNumber: '8'
}, organisation: {name: 'oh'}})
}
createForm(user: any) {
this.userForm = this.fb.group({
name: user.profileData.name,
email: user.profileData.email,
phone: user.profileData.mobileNumber,
orgForm: this.fb.group({
name: [ user.organisation.name , [Validators.required]]
})
});
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
}
}