无法以反应性角度形式定义表单组

时间:2018-08-28 22:46:24

标签: angular angular6 angular-reactive-forms

我正在尝试在反应式表单中创建一个formGroup。这包括一些我想观察两者都有哪些更改的字段。我正在按照official guide的指示进行操作,但仍然出现错误。

这是我的代码

      <form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">
        <div [formGroup]="myFormNameDrop">
            <label>
                <input type="text" formControlName="myName" required >
              </label>
              <label>
                  <select name="myDrop" selected formControlName="myDrop" (change)="myDropChanged($event)">
                    <option value="era" >era</option>                      
                    <option value="plate">plate</option>
                  </select>
              </label>
            </div><!-- myFormNameDrop-->

       <!-- more dropdowns -->
       <button type="submit">Submit</button>
      </form>

我如何在组件中定义表单

  myForm = this.formBuilder.group({
    myFormNameDrop: this.formBuilder.group({
      myName:['',Validators.required],
      myDrop:['era']
    }),    
    day:[''],
    type:[''],
    style:[''],
    userId:[this.user_id]
  });

然后我想做

this.data = this.myForm.myFormNameDrop.valueChanges.pipe(

但是我收到以下错误

`错误错误:formGroup需要一个FormGroup实例。请传递一个。

   Example:


<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});
at Function.push../node_modules/@angular/forms/fesm5/forms.js.ReactiveErrors.missingFormException (forms.js:994)
at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective._checkFormPresent (forms.js:4382)
at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.ngOnChanges (forms.js:4292)
at checkAndUpdateDirectiveInline (core.js:8935)
at checkAndUpdateNodeInline (core.js:10203)
at checkAndUpdateNode (core.js:10165)
at debugCheckAndUpdateNode (core.js:10798)
at debugCheckDirectivesFn (core.js:10758)
at Object.eval [as updateDirectives] (MapcmsComponent.html:106)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:10750)`

tha是关于这条线<form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">

请帮助我进行调试。我使用Angular 6

谢谢

1 个答案:

答案 0 :(得分:2)

使用formGroupName="myFormNameDrop"

 <form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">
   <div formGroupName="myFormNameDrop">
   </div>
 </form>

FormControl:

 myDrop:['era'] can be simplified as  myDrop:'era'