Angular 4从模态获得形式值

时间:2017-05-05 00:24:17

标签: angular ng-bootstrap

在提交表单时,我遇到了从模式中获取表单值的问题。日志说addMountForm是未定义的。我提供了我的html和组件的代码片段。我很感激你的帮助。

<ng-template #content let-c="close" let-d="dismiss">
   <div class="modal-header">
      <h3 class="modal-title">Add Mount Point</h3>
   </div>
   <div class="modal-body">
      <form (ngSubmit)="onSubmit()" #addMountForm="ngForm" >
         <div class="form-group">
            <label class="col-sm-2 control-label text-nowrap"
               for="archiveOrigin">Archive Origin</label>
            <div class="col-sm-10">
               <input type="text" class="form-control" ngModel id="archiveOrigin" name="archiveOrigin" placeholder="Archive Origin"/>
            </div>
         </div>

               <button type="submit" class="btn btn-default">Add</button>

      </form>
   </div>
   <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="c('Close click')">
      Close
      </button>
   </div>
</ng-template>
<div class="page pt-2">

</div>


@Component({
  selector: 'mount-point',
  templateUrl: './mountpoint.component.html',
  styleUrls: ['./mountpoint.component.scss']
})
export class MountPointComponent implements OnInit {

@ViewChild('addMountForm') addMountForm : NgForm;

  constructor(
    private modalService: NgbModal
  ){}




  open(content) {
      this.modalService.open(content).result.then((result) => {
         console.log("closed");
      }, (reason) => {
         console.log("dismissed" );
      });
   }

  onSubmit(){
    console.log("adding form values ");
    console.log(this.addMountForm);
}

}

3 个答案:

答案 0 :(得分:6)

  1. 仅使用[(ngModel)]="value"代替ngModel

  2. (ngSubmit)="onSubmit()"更改为(ngSubmit)="onSubmit(addMountForm)"

    并在组件中

    onSubmit(form: NgForm){
      console.log(form.value);
    }
    

答案 1 :(得分:2)

您的代码是正确的。正如其他人所说,你需要通过onSubmit方法传递你的表单,因为它在模板中,这就是你无法通过@ViewChild访问它的原因。

onSubmit(form){
console.log("adding form values ");
console.log(form.value.archiveOrigin);
}

Plunker

此外,如果您不想使用绑定,则不需要为ngModel使用香蕉盒[()]

我建议你看一下模板驱动和模型驱动设计之间的this比较。

答案 2 :(得分:0)

1)导入NgForm

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

2)将表单定义更改为此

<form (ngSubmit)="onSubmit(addMountForm)" #addMountForm="ngForm" >

3)将您的组件更改为此

 import { Component, OnInit } from '@angular/core';
 import {NgForm} from '@angular/forms';
 @Component({
  selector: 'mount-point',
  templateUrl: './mountpoint.component.html',
  styleUrls: ['./mountpoint.component.scss']
})
export class MountPointComponent implements OnInit {

  constructor(
    private modalService: NgbModal
  ){}

 ngOnInit(){

  }

  open(content) {
      this.modalService.open(content).result.then((result) => {
         console.log("closed");
      }, (reason) => {
         console.log("dismissed" );
      });
   }

  onSubmit(addMountForm: NgForm){
    console.log("adding form values ");
    console.log(addMountForm.value);
}

}

这样就行了,你将在控制台上得到一个包含所有表单值的对象。