Post Data from two forms as one Object in Angular

后端 未结 2 1699
无人及你
无人及你 2021-01-22 18:10

This is my first project on Angular and I have done as much as I could and I will try to finish it myself but I feel like that I require help.

A brief description of th

相关标签:
2条回答
  • 2021-01-22 18:52

    You can do it like this create a finalData array where you can accumulate the data you receive from your form1 and form2 and when user finally click on save button you can send data of finalData.

      form1Data = [];
      form2Data = [];
      finalData = [];
    
      saveClause(form  :NgForm){
        console.log("Form Values",form.value);
        this.form1Data = form.value;
        this.show1 = true
      }
    
      addFilter(filter : NgForm){
        console.log("FilterForm Value",filter.value)
        this.form2Data = filter.value;
        this.finalData.push({
          ...this.form1Data,
          ...this.form2Data
        });
    
        console.log(this.finalData);
    
        filter.reset()
      }
    

    working demo : link

    Note : see console for final result.

    0 讨论(0)
  • 2021-01-22 19:01

    If you want to merge form data from both objects you can do:

    finalData = {};
    
    saveClause(form: NgForm) {
       this.show1 = true;
       Object.assign(this.finalData, form.value);
    }
    
    addFilter(filter: NgForm) {
       Object.assign(this.finalData, filter.value);
       filter.reset();
    } 
    

    Now depending on your use case you can decide when to post this data to the backend.


    EDIT:

    Since you want to merge into a single object use:

    finalPostArray = [];
    mergedObj = {};
    
    saveClause(form: NgForm) {
       ... 
       Object.assign(this.mergedObj, form.value);
       this.finalPostArray.push(this.mergedObj);
       ... 
    }
    
    addFilter(filter: NgForm) {
       Object.assign(this.mergedObj, filter.value);
       filter.reset();
    }
    

    Working stackblitz

    0 讨论(0)
提交回复
热议问题