2

I have worked with template driven forms before and I am slightly confused how the reactive forms work to store the data to my database. Initially I would just use [(ngModel)]="user.date". How do I store the data now on submit? I have built one as follows:

this.formGroup = this._formBuilder.group({
  formArray: this._formBuilder.array([
    this._formBuilder.group({
      dateFormCtrl: ['', Validators.required]
    }),
    this._formBuilder.group({
      emailFormCtrl: ['', Validators.email]
    }),
  ])
});

Here's an example of an input that I want to store to the db:

<input formControlName="dateFormCtrl" matInput [matDatepicker]="picker" [max]="maxDate" [min]="minDate" placeholder="When is your event?"(click)="picker.open()" readonly>

ATM I have this function which I built for the template driven form to store data:

 create() {
    this.http.post('http://localhost:3000/user', this.user).subscribe(res => { ............

2 Answers 2

2

your form should be like

 this.form = this._formBuilder.group({
       dateFormCtrl: ['', Validators.required],
       emailFormCtrl: ['', Validators.email]
    });

Your submit method should be like

   onSubmit(): void{
       const formObj ={
        date: this.form.value.dateFormCtrl,
        email: this.form.value.emailFormCtrl,
       }
      this.http.post('http://localhost:3000/user', formObj).subscribe(res =>
    }
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to save form data to a server dynamically, then you can follow the below code. It is the best available option.

In your component.ts file:

  form: FormGroup;
  payLoad = '';

    onSubmit() {
        this.payLoad = JSON.stringify(this.form.value);

        this.serverService.storeServers(this.payLoad)
        .subscribe(
          (response) => console.log(response),
          (error) => console.log(error)
        );

      }

In your service.ts file:

constructor(private http: HttpClient) { }
  storeServers(payLoad: any) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json'
      })
    };
    return  this.http.post(' ***Complete URL*** ', payLoad, httpOptions);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.