首页 > 解决方案 > 离子 - 表单无法提交要保存到数据库的数组

问题描述

我想在提交表单后将数组评论推送到cabine.comments 数组中。我已经创建了我的表单,但我收到一条错误消息:

错误错误:未捕获(承诺):错误:模板解析错误:无法绑定到“formGroup”,因为它不是“form”的已知属性。("

我正在使用 JSON 数据库。

我对离子真的很陌生,我迷路了。

这是我的表格

  <form [formGroup]="commentform" (ngSubmit)="onSubmit()">
  <ion-item>
    <ion-label>Name</ion-label>
    <ion-input type="text" formControlName="author"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label>Rating</ion-label>
    <ion-input type="text" formControlName="rating"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label>Comment</ion-label>
    <ion-textarea formControlName="comment"></ion-textarea>
  </ion-item>
  <button ion-button type="submit" [disabled]="!commentForm.valid">Submit</button>
</form>

这是我的客舱页面

import { Component, OnInit } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { CabinService } from '../../services/cabin.service';
import { ActivatedRoute, Router } from '@angular/router'
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Location } from '@angular/common';

@Component({
  selector: 'app-cabin-detail',
  templateUrl: './cabin-detail.page.html',
  styleUrls: ['./cabin-detail.page.scss'],
})
export class CabinDetailPage implements OnInit {


  cabin: any = {};
  comment: any;

   cabins: any;
  commentform: FormGroup;
  errMess: any;


  formErrors = {
    'author' : '',
    'rating' : '',
    'comment' : ''
  };

  validationMessages = {
    'author' : {
      'required' : 'Name is required',
      'minlength' : 'Name must be at least 2 characters long',
      'maxlength' : 'Name cannot be more that 25 characters long'
    }
  };

  constructor(public api: CabinService,
      public loadingController: LoadingController,
      private fb: FormBuilder,
      private location: Location,
      public route: ActivatedRoute,
      public router: Router) {
this.createForm();
      }


  async getCabin() {
  const loading = await this.loadingController.create();
  await loading.present();
  await this.api.getCabinById(this.route.snapshot.paramMap.get('id'))
    .subscribe(res => {
      console.log(res);
      this.cabin = res;
      loading.dismiss();
    }, err => {
      console.log(err);
      loading.dismiss();
    });
}

 ngOnInit() {
  this.getCabin();
}



    createForm() {
    this.commentform = this.fb.group({
      author: ['', [ Validators.required, Validators.minLength(2) ] ],
      rating: 5,
      comment: ['', [ Validators.required ] ],
    });

    this.commentform.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set form validation messages
  }

    onValueChanged(commentformData?: any) {
    if (!this.commentform) {
      return;
    }
    const form = this.commentform;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }

    if (this.commentform.valid) {
      this.comment = this.commentform.value;
    } else {
      this.comment = undefined;
    }
  }


  onSubmit() {
      const id = +this.route.snapshot.paramMap.get('id');

    this.cabin.comments.push(this.comment);
    this.api.updateComment(this.cabin.id, this.comment).subscribe(() => {
    console.log("PUT is done");
})

  }





}

我的服务保存到数据库

updateComment(id, newcomment) {
const comment: Comment = newcomment;
return this.http.get<any>('http://localhost:3000/cabins/' + id).pipe(
  map(cabin => {


    return {
      id: cabin.id,
      name: cabin.name,
      image: cabin.image,
      description: cabin.description,
      priceweek: cabin.priceweek,
      pricemonth: cabin.pricemonth,
      featured: cabin.featured,
      comments: cabin.comments


    };


  }),
  flatMap((updatedCabin) => {
    updatedCabin.comments.push(comment);
    return this.http.put( + '/' + id, updatedCabin);
  })
);

}

这是我的项目的堆栈闪电战https://stackblitz.com/edit/ionic-xjq8ic?embed=1&file=app/pages/cabin-detail/cabin-detail.page.html

标签: angulartypescriptionic-framework

解决方案


你需要

import { ReactiveFormsModule } from '@angular/forms';

进入你的模块。

例如

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 
import { AppComponent }  from './app.component';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent] })

export class AppModule { }

这将解决这个问题


推荐阅读