首页 文章

formGroup需要一个FormGroup实例 . 请通过一个 . 角4

提问于
浏览
0

我找到了这个问题的多种解决方案,但没有一个正常 .

这是我的角色形式

<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获得 Value .

1 回答

  • 1

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

    try : <div [formGroup]="restaurantForm.controls['location']">

    instead of : [formGroup]="location"

    希望这有帮助:)

相关问题