【问题标题】:formGroup expects a FormGroup instance. Please pass one in. angular 4formGroup 需要一个 FormGroup 实例。请通过一英寸角 4
【发布时间】:2017-10-27 06:57:52
【问题描述】:

我为这个问题找到了多种解决方案,但没有一个有效。

这是我的角形

<div class="container">
 <form   [formGroup]="restaurantForm" novalidate>
 <div class="form-group">
  <label for="rating">Rest Name</label>
  <input type="text" class="form-control" formControlName="restName" />
 </div>

<div class="form-group">
  <label for="alterEgo">Description</label>
  <input type="text" class="form-control" formControlName="description" />
</div>

<div [formGroup]="location">

  <div class="form-group">
    <label for="alterEgo">Latitude</label>
    <input type="text" class="form-control" formControlName="latitude">
  </div>
  <div class="form-group">
    <label for="alterEgo">Longitude</label>
    <input type="text" class="form-control" formControlName="longitude">
  </div>
  <div class="form-group">
    <label for="alterEgo">Street</label>
    <input type="text" class="form-control" formControlName="street">
  </div>
  <div class="form-group">
    <label for="alterEgo">Road No</label>
    <input type="text" class="form-control" formControlName="roadNo">
  </div>

</div>

</form>
</div>

<button type="submit" class="btn btn-success" (click)="newRestaurant()">Submit</button>

这是我使用 Formbuilder 和 FormGroup 指定表单初始化的组件。

@Component({
selector: 'restaurant',
templateUrl: 'restaurantForm.component.html'
})

export class ResComponent implements OnInit {

restaurantForm: FormGroup;
restaurants = [];

constructor(private fb: FormBuilder) {
this.restaurantForm = this.fb.group({
  restName: '',
  description: '',
  location: fb.group({
    latitude: '',
    longitude: '',
    street: '',
    roadNo: '',
  })
});
}

ngOnInit() {
}



 newRestaurant() {
 let res = { "restaurant": this.restaurantForm.value };
 this.restaurants.push(res);
 alert(JSON.stringify(this.restaurantForm.value));

 }

}

当我加载此表单时,我收到一个错误,例如“formGroup 需要一个 FormGroup 实例。请传入一个。”我尝试了上一篇文章中的多种解决方案,但都没有奏效。当我提交表单时,我没有从“位置”formGroup 中获得价值。

【问题讨论】:

  • 你能展示你的 HTML 模板的其余部分吗?至少你的divform 结束
  • 嗨 rachid,我编辑我的问题
  • 您的班级中没有location 属性?你期待什么?
  • [formGroup]="location" 替换为formGroupName="location"
  • 在构造函数@yuruzi.

标签: angular angular-reactive-forms


【解决方案1】:

当你写 [formGroup]="location" 时,这意味着在你的 ts 中有一个 FormGroup 的实例称为 location ,所以你必须传递 restaurantForm.controls['location'] 的实例

试试: &lt;div [formGroup]="restaurantForm.controls['location']"&gt;

而不是: [formGroup]="location"

希望有帮助:)

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 2020-06-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多