Ionic - form not working to submit a array to be saved to database











up vote
1
down vote

favorite












I want to push an array comment in to cabin.comments array after a form is submited.
I have created my form but I am getting a error saying:



ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'formGroup' since it isn't a known property of 'form'. ("



I am using a JSON database.



I am really new to ionic and I am lost.



this is my form



  <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>


This is my cabin page



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");
})

}





}


My service to save to the database



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);
})
);


}



This is a stackblitz to my project https://stackblitz.com/edit/ionic-xjq8ic?embed=1&file=app/pages/cabin-detail/cabin-detail.page.html










share|improve this question


























    up vote
    1
    down vote

    favorite












    I want to push an array comment in to cabin.comments array after a form is submited.
    I have created my form but I am getting a error saying:



    ERROR Error: Uncaught (in promise): Error: Template parse errors:
    Can't bind to 'formGroup' since it isn't a known property of 'form'. ("



    I am using a JSON database.



    I am really new to ionic and I am lost.



    this is my form



      <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>


    This is my cabin page



    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");
    })

    }





    }


    My service to save to the database



    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);
    })
    );


    }



    This is a stackblitz to my project https://stackblitz.com/edit/ionic-xjq8ic?embed=1&file=app/pages/cabin-detail/cabin-detail.page.html










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I want to push an array comment in to cabin.comments array after a form is submited.
      I have created my form but I am getting a error saying:



      ERROR Error: Uncaught (in promise): Error: Template parse errors:
      Can't bind to 'formGroup' since it isn't a known property of 'form'. ("



      I am using a JSON database.



      I am really new to ionic and I am lost.



      this is my form



        <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>


      This is my cabin page



      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");
      })

      }





      }


      My service to save to the database



      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);
      })
      );


      }



      This is a stackblitz to my project https://stackblitz.com/edit/ionic-xjq8ic?embed=1&file=app/pages/cabin-detail/cabin-detail.page.html










      share|improve this question













      I want to push an array comment in to cabin.comments array after a form is submited.
      I have created my form but I am getting a error saying:



      ERROR Error: Uncaught (in promise): Error: Template parse errors:
      Can't bind to 'formGroup' since it isn't a known property of 'form'. ("



      I am using a JSON database.



      I am really new to ionic and I am lost.



      this is my form



        <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>


      This is my cabin page



      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");
      })

      }





      }


      My service to save to the database



      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);
      })
      );


      }



      This is a stackblitz to my project https://stackblitz.com/edit/ionic-xjq8ic?embed=1&file=app/pages/cabin-detail/cabin-detail.page.html







      angular typescript ionic-framework






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 20:29









      user3149979

      228




      228
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          you need to



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


          into your module.



          e.g



          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 { }


          this will fix this issue






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269639%2fionic-form-not-working-to-submit-a-array-to-be-saved-to-database%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            you need to



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


            into your module.



            e.g



            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 { }


            this will fix this issue






            share|improve this answer



























              up vote
              1
              down vote



              accepted










              you need to



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


              into your module.



              e.g



              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 { }


              this will fix this issue






              share|improve this answer

























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                you need to



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


                into your module.



                e.g



                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 { }


                this will fix this issue






                share|improve this answer














                you need to



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


                into your module.



                e.g



                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 { }


                this will fix this issue







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 12 at 20:44

























                answered Nov 12 at 20:35









                Nitin Walia

                39818




                39818






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269639%2fionic-form-not-working-to-submit-a-array-to-be-saved-to-database%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Guess what letter conforming each word

                    Port of Spain

                    Run scheduled task as local user group (not BUILTIN)