如何从输入字段绑定对象数组的成员

时间:2017-11-27 10:44:36

标签: angular typescript

我有一个表单字段,我希望将用户插入的数据绑定到typescript文件中创建的对象。

<form (ngSubmit)="onSubmitTest()">
  <div class="form-group">
    <label for="name"><strong>Name</strong></label>
    <input type="text" [(ngModel)]="testBody.test_name" class="form-control" name="name">
  </div>



  <div class="row">
    <div class="col-sm-6">
      <div class="form-group">
        <label for="date"><strong>Date</strong></label>
        <div class="input-group">
          <input type="date" class="form-control" name="date">
        </div>
      </div>
      <div class="form-group">
        <label for="duration"><strong>Duration</strong></label>
        <div class="input-group">
          <input type="number" [(ngModel)]="testBody.test_duration" class="form-control" name="duration">
          <span class="input-group-addon" id="basic-addon2">mins</span>
        </div>
      </div>



      <div class="form-group">
        <label for="class"><strong>Class</strong></label>
        <input type="text" [(ngModel)]="testBody.test_class" class="form-control" name="class">
      </div>

      <div class="form-group">
        <label for="lang"><strong>Language</strong></label>
        <input type="text" [(ngModel)]="testBody.test_language" class="form-control" name="lang">
      </div>

      <div class="form-group">
        <label for="strTag"><strong>Store Tag</strong></label>
        <input type="text" class="form-control" name="strTag">
      </div>
    </div>
    <div class="col-sm-6">
      <div class="form-group">
        <label for="time"><strong>Time range</strong></label>
        <div class="input-group">
          <input type="time" class="form-control" name="timestart">
          <span class="input-group-addon" id="basic-addon2">TO</span>
          <input type="time" class="form-control" name="timeend">
        </div>
      </div>

      <div class="form-group">
        <label for="code"><strong>Code</strong></label>
        <div class="input-group">
          <input type="text" class="form-control">
          <span class="input-group-btn">
                                                                            <button class="btn btn-default" type="button"><i class="fa fa-search" aria-hidden="true"></i></button>
                                                                    </span>
        </div>
      </div>

      <div class="form-group">
        <label for="exam"><strong>Exam</strong></label>
        <input type="text" [(ngModel)]="testBody.test_exam" class="form-control" name="exam">
      </div>

      <div class="form-group">
        <label for="board"><strong>Board</strong></label>
        <input type="text" [(ngModel)]="testBody.test_board" class="form-control" name="board">
      </div>

      <div class="form-group">
        <label for="price"><strong>Price</strong></label>
        <div class="input-group">
          <span class="input-group-addon" id="basic-addon2">Rs.</span>
          <input type="number" class="form-control" name="price">
        </div>
      </div>
    </div>

  </div>


  <div class="form-group">
    <label for="desc"><strong>Description</strong></label>
    <input type="text" [(ngModel)]="testBody.test_instruction" class="form-control" name="desc">
  </div>

  <div>
    <label for="section"><strong>SECTION</strong></label>
    <div *ngFor="let i of sectionNumber; let section of testBody.test_sections_data">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon2">{{i}}</span>
        <input type="text" [(ngModel)]="section.section_name" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="questionNo"><strong>Ques.</strong></label>
        <input type="number" [(ngModel)]="section.section_number_of_questions" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="maxMarks"><strong>Max marks</strong></label>
        <input type="number" [(ngModel)]="section.section_max_marks" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="cuttOff"><strong>Cut off</strong></label>
        <input type="number" [(ngModel)]="section.section_cut_off" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="cuttOff"><strong>Topper mark</strong></label>
        <input type="number" [(ngModel)]="section.section_topper_marks" class="form-control" [ngModelOptions]="{standalone: true}">
      </div>
    </div>

    <button type="button" style="margin:10px" (click)="incrementSection()" class="btn btn-sm btn-info">+</button>
  </div>



  <div class="row">
    <div class="col-md-6">
      <p><strong>MARKS RANGE</strong></p>
      <div class="form-group">

        <div class="input-group">
          <input type="number" class="form-control" id="from">
          <span class="input-group-addon" id="basic-addon2">TO</span>
          <input type="number" class="form-control" id="to">
        </div>
        <div class="input-group">
          <input type="number" class="form-control" id="from">
          <span class="input-group-addon" id="basic-addon2">TO</span>
          <input type="number" class="form-control" id="to">
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <p><strong>RANK RANGE</strong></p>
      <div class="input-group">
        <input type="number" class="form-control" id="from">
        <span class="input-group-addon" id="basic-addon2">TO</span>
        <input type="number" class="form-control" id="to">
      </div>
      <div class="input-group">
        <input type="number" class="form-control" id="from">
        <span class="input-group-addon" id="basic-addon2">TO</span>
        <input type="number" class="form-control" id="to">
      </div>

    </div>
  </div>


  <div class="form-group">
    <label for="visible"><strong>Visible</strong></label>
    <input type="checkbox" [(ngModel)]="testBody.test_visibility" name="visibleTest" [checked]="isVisible" (change)="isVisible=!isVisible">
  </div>



  <button type="submit" class="btn btn-default">Add</button>
  <button type="submit" class="btn btn-default pull-right">Export File</button>
</form>

这就是它在后端绑定的内容。

export class TestDetailComponent implements OnInit {
  sectionSno = 1;
  sectionNumber = [1];
  isVisible = true;
  program_id: string;
  testCategory: string[];
  testName: string[];
  closeResult: string;
  body: {
    category_name: string,
    description: string,
    code: string,
    store_tag: string,
    visible: number,
    client_id: string,
    program_id: string
  };

  testBody: {
    test_category: string,
    test_instruction: string,
    test_duration: string,
    test_name: string,
    test_class: string,
    test_language: string,
    test_exam: string,
    test_board: string,
    client_id: string,
    program_id: string,
    test_visibility: number,
    test_sections_data: [{
      section_name: string,
      section_max_marks: number,
      section_cut_off: number,
      section_topper_marks: number,
      section_number_of_questions: number
    }]
  }

  // tslint:disable-next-line:max-line-length
  constructor(private modalService: NgbModal, private route: ActivatedRoute, private dragulaService: DragulaService, private http: HttpClient) {
    const bag: any = this.dragulaService.find('bag-task1');
    this.body = {
      category_name: '',
      description: '',
      code: '',
      store_tag: '',
      visible: null,
      client_id: allGlobals.client_id,
      program_id: this.program_id
    };
    this.testBody = {
      test_category: '',
      test_instruction: '',
      test_duration: '',
      test_name: '',
      test_class: '',
      test_language: '',
      test_exam: '',
      test_board: '',
      client_id: allGlobals.client_id,
      program_id: this.program_id,
      test_visibility: null,
      test_sections_data: null
    };
    this.body.visible = 0;
    if (bag !== undefined) {
      this.dragulaService.destroy('bag-task1');
    }
    this.dragulaService.setOptions('bag-task1', {
      copy: false
    });
    this.http.get(allGlobals.url_server + '/getTestCategories?client_id=' + allGlobals.client_id).subscribe(data => {
      // Read the result field from the JSON response.get response
      this.testCategory = data['rows'];
    });
    this.http.get(allGlobals.url_server + '/getTestList?client_id=' + allGlobals.client_id).subscribe(data => {
      // Read the result field from the JSON response.
      this.testName = data['rows'];
    });
  }


  open(content) {
    this.modalService.open(content).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  getVisibleInt() {
    if (this.isVisible === true) {
      this.body.visible = 1;
    } else {
      this.body.visible = 0;
    }
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }

  incrementSection() {
    this.sectionSno++;
    this.sectionNumber.push(this.sectionSno);
  }

  setCategoryId(category) {
    this.testBody.test_category = category.testCategories_id;
  }

  onSubmit() {
    this.http.post(allGlobals.url_server + '/addTestCategory', this.body)
      .subscribe(data => {
          this.http.get(allGlobals.url_server + '/getTestCategories?client_id=' + allGlobals.client_id).subscribe(data => {
            // Read the result field from the JSON response.get response
            this.testCategory = data['rows'];
          });
          this.http.get(allGlobals.url_server + '/getTestList?client_id=' + allGlobals.client_id).subscribe(data => {
            // Read the result field from the JSON response.
            this.testName = data['rows'];
          });
        },
        err => {
          console.log(err);
        },
        () => {
          this.body = {
            category_name: '',
            description: '',
            code: '',
            store_tag: '',
            visible: null,
            client_id: allGlobals.client_id,
            program_id: this.program_id
          }
        }
      );
  }

  onSubmitTest() {
    this.http.post(allGlobals.url_server + '/addTest', this.testBody)
      .subscribe(data => {
          this.http.get(allGlobals.url_server + '/getTestCategories?client_id=' + allGlobals.client_id).subscribe(data => {
            // Read the result field from the JSON response.get response
            this.testCategory = data['rows'];
          });
          this.http.get(allGlobals.url_server + '/getTestList?client_id=' + allGlobals.client_id).subscribe(data => {
            // Read the result field from the JSON response.
            this.testName = data['rows'];
          });
        },
        err => {
          console.log(err);
        },
        () => {
          this.testBody = {
            test_category: '',
            test_instruction: '',
            test_duration: '',
            test_name: '',
            test_class: '',
            test_language: '',
            test_exam: '',
            test_board: '',
            client_id: allGlobals.client_id,
            program_id: this.program_id,
            test_visibility: null,
            test_sections_data: null
          };
        }
      )
  }




  ngOnInit() {
    this.route.params.subscribe(params => {
      this.program_id = params['id']; // --> Name must match wanted parameter
      this.body.program_id = this.program_id;
      this.testBody.program_id = this.program_id;
    });
  }

}

现在,当我添加测试部分时,我在后端获取null,而所有其他字段都被分配。我不知道我是否做得对,但是test_sections_data是一个对象数组,每次点击+按钮时,该部分的编号都会递增。

1 个答案:

答案 0 :(得分:0)

试试这个:

<div *ngFor="let section of testBody.test_sections_data; let i = index">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon2">{{i}}</span>
        <input type="text" [(ngModel)]="testBody.test_sections_data[i].section_name" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="questionNo"><strong>Ques.</strong></label>
        <input type="number" [(ngModel)]="testBody.test_sections_data[i].section_number_of_questions" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="maxMarks"><strong>Max marks</strong></label>
        <input type="number" [(ngModel)]="testBody.test_sections_data[i].section_max_marks" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="cuttOff"><strong>Cut off</strong></label>
        <input type="number" [(ngModel)]="testBody.test_sections_data[i].section_cut_off" class="form-control" [ngModelOptions]="{standalone: true}">
        <label for="cuttOff"><strong>Topper mark</strong></label>
        <input type="number" [(ngModel)]="testBody.test_sections_data[i].section_topper_marks" class="form-control" [ngModelOptions]="{standalone: true}">
      </div>
 </div>

修改添加部分功能:

incrementSection() {
    let sec:any = {}; 
    this.testBody.test_sections_data.push(sec);
  }

constructor(){
    this.testBody = {
          test_category: '',
          test_instruction: '',
          test_duration: '',
          test_name: '',
          test_class: '',
          test_language: '',
          test_exam: '',
          test_board: '',
          client_id: allGlobals.client_id,
          program_id: this.program_id,
          test_visibility: null,
          test_sections_data: [{
           section_name: '',
           section_max_marks: 0,
           section_cut_off: 0,
           section_topper_marks: 0,
           section_number_of_questions: 0
           }]
        };
}