我正在使用组件添加表单输入字段 –
发动机附加接触form.html
<form (ngSubmit)="onSubmit()" [formGroup]="contact_form"> <md-tab-group> <md-tab label="Form"> <ang-form></ang-form> </md-tab> <md-tab label="Email"> <ang-email></ang-email> </md-tab> <md-tab label="Message"> <ang-message></ang-message> </md-tab> </md-tab-group> <button md-raised-button type="submit">Publish</button>
ANG-form.html
<div class="form-grid form-title"> <md-input-container> <input formControlName="contact_form_title" class="form-title-field" mdInput placeholder="Title" value=""> </md-input-container> </div>
使用相同的方式我添加了其他组件(ang-email ang-message)html.
我在engine-add-form.ts中添加了[formGroup]指令
export class EngineAddFormComponent{ contact_form: any; form_value: any; constructor(){ this.contact_form = new FormGroup({ contact_form_title: new FormControl('',Validators.minLength(2)),........ ........ }); } onSubmit(){ this.form_value = JSON.stringify(this.contact_form.value); console.log(this.form_value); } }
我收到以下错误 –
Error: formControlName must be used with a parent formGroup directive.
You’ll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).
我无法理解我的代码有什么问题.
您需要将formGroup(在您的情况下为contact_form)传递给ang-form的子组件
发动机附加接触form.html(修改)
<form (ngSubmit)="onSubmit()" [formGroup]="contact_form"> <md-tab-group> <md-tab label="Form"> <ang-form [group]="contact_form"></ang-form> </md-tab> <md-tab label="Email"> <ang-email></ang-email>`` </md-tab> <md-tab label="Message"> <ang-message></ang-message> </md-tab> </md-tab-group> <button md-raised-button type="submit">Publish</button>
ANG-form.html(修改)
<div class="form-grid form-title" [formGroup]="group"> <md-input-container> <input formControlName="contact_form_title" class="form-title-field" mdInput placeholder="Title" value=""> </md-input-container> </div>
Add @Input() group: FormGroup; in your ang-form.component.ts