Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 get form value from modal

I am having issues to get the form value from the modal when I submit the form. The log says the addMountForm is undefined. I have provided code snippets of my html as well as component. I would appreciate your help.

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

}
like image 368
rvd Avatar asked May 05 '17 00:05

rvd


2 Answers

  1. Use [(ngModel)]="value" instead of ngModel alone.

  2. Change (ngSubmit)="onSubmit()" to (ngSubmit)="onSubmit(addMountForm)"

    and in the component

    onSubmit(form: NgForm){
      console.log(form.value);
    }
    
like image 122
digit Avatar answered Nov 18 '22 09:11

digit


Your code was correct. Just as others said you need to pass your form through onSubmit method because it is inside a template and that's why you can't access to it by @ViewChild.

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

Plunker

Also, you don't need to use banana box [()] for ngModel if you don't want to use binding.

I recommend you see this comparison between template-driven and model-driven design.

like image 34
M_Farahmand Avatar answered Nov 18 '22 09:11

M_Farahmand