Having trouble retrieving input values from forms in Angular 2?

Currently, I am using a modal form that loads information about my items when it is open. However, when I try to submit, all inputs are null except when the modal displays which works fine.

<div id="modal1" class="modal">
  <form #formData='ngForm' (ngSubmit)="onSubmit(formData)">
    <div class="modal-content">
      <div class="row">    
        <div class="input-field col s6">
          <input (ngModel)="productN" value="{{ObjProd.product}}"  name="productN" type="text"  >
          <label for="productN">Product Name</label>
        </div>
        <div class="input-field col s6">
          <input (ngModel)="price" value="{{ObjProd.price}}"  name="price" type="text"  >
          <label for="price">price</label>
        </div>
        <div class="input-field col s6">
          <input (ngModel)="quantity" value="{{ObjProd.quantity}}"   name="quantity" type="text"  >
          <label for="quantity">quantity</label>
        </div>
        <div class="input-field col s6">
          <input (ngModel)="photoURL" value="{{ObjProd.product}}"   name="photoURL" type="text"  >
          <label for="photoURL">photoURL</label>

        </div>
         <input type="text" placeholder="Full name" value="{{ObjProd.key}}" (ngModel)="namef" name="namef" class="txt" >
        <input type="text" (ngModel)="keyProduct"   name="keyProduct" value="{{ObjProd.key}}" >
        <input type="text" (ngModel)="typeProduct"   name="typeProduct" value="{{ObjProd.type}}" >
      </div>
    </div>
    <div class="modal-footer">
      <button type="submit"  class="modal-action modal-close waves-effect waves-green btn-flat " >Update Product</button>
    </div>
  </form>
</div>

Upon submission, the function will check if there is a type of product specified and log the photo URL. Otherwise, it will log both the name and photo URL.

  onSubmit(formData) {
    if(formData.value.typeProduct){
      console.log(formData.value.photoURL);
    }else{
      console.log(formData.value.namef, formData.value.photoURL);
    }

    }

The modal works correctly displaying data, but there seems to be an issue with the output. Check this link for more details.

Answer №1

Your code is currently located in the index.html file and utilizing jQuery, causing issues with the application.

It is recommended to utilize a modal component as a separate entity, as shown below:

import {Component,Input, ViewChild} from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'common-modal',
  template: `
   <div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title pull-left">{{title}}</h4>
        <button type="button" class="close pull-right" aria-label="Close" (click)="hideChildModal()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form #formData='ngForm' (ngSubmit)="onSubmit(formData)">
    <div class="modal-content">
      <div class="row">    
        <div class="input-field col s6">
          <input [(ngModel)]="productN" value="true"  name="productN" type="text"  >
          <label for="productN">Product Name</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="price" value="true"  name="price" type="text"  >
          <label for="price">price</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="quantity" value="true"   name="quantity" type="text"  >
          <label for="quantity">quantity</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="photoURL" value="true"   name="photoURL" type="text"  >
          <label for="photoURL">photoURL</label>

        </div>
         <input type="text" placeholder="Full name" value="true" [(ngModel)]="namef" name="namef" class="txt" >
        <input type="text" [(ngModel)]="keyProduct"   name="keyProduct" value="true" >
        <input type="text" [(ngModel)]="typeProduct"   name="typeProduct" value="true" >
      </div>
    </div>
    <div class="modal-footer">
      <button type="submit"  class="modal-action modal-close waves-effect waves-green btn-flat " >Update Product</button>
    </div>
  </form>
      </div>

      <div class="modal-footer">
        <div class="pull-left">
          <button class="btn btn-default" (click)="hide()"> Cancel </button>
        </div>
      </div>
    </div>
  </div>
</div>
  `,
})
export class CommonModalComponent {
   @ViewChild('childModal') public childModal:ModalDirective;
   @Input() title?:string;
  constructor() {
  }
  show(){
    this.childModal.show();
  }
  hide(){
    this.childModal.hide();
  }
  onSubmit(val){
    console.log(val);
  }
}

LIVE DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Put your username onto the page

Is there a method to retrieve and display text inputs? For example: document.getElementById('input_id') <input type="text" placeholder="username" id="input_id"> and the result will be: document.showElementById('box_id') < ...

Is there a way to center the pagination at the bottom of the screen?

I want to position my pagination at the bottom-center of the page using Angular Material's mat-paginator component. Currently, this is what it looks like: 1: https://i.sstatic.net/21mUj.png 2: https://i.sstatic.net/kfXH6.png The issue I'm fac ...

Can someone share tips on creating a stylish vertical-loading progress bar with a circular design?

Currently, I am working on developing a unique progress bar that resembles a glass orb filling up with liquid. However, due to its rounded shape, the traditional approach of adjusting the height does not produce the desired result (as illustrated in this f ...

I ran into an issue trying to generate a React app using the command "npx create-react-app" and was unable to proceed

When I attempted to run the command npx create-react-app my-app, I encountered an error: (ps: I also tried running npm init and npm install create-react-app before executing the aforementioned command, but still got the same error.) HELP! Installing pack ...

Is there a way to retrieve an array generated within a JavaScript loop?

I've been working on retrieving column values from a database and storing them in an array, but I keep getting an empty array as the result. function FetchData(query, db) { var resultArray = new Array(); db.transaction(function(tx) { tx.executeSq ...

If the button is clicked in jQuery, then perform a specific action; otherwise, execute

hello, I am encountering difficulties in getting this feature to function properly. I am utilizing cropbox to allow users to upload their logos. The issue arises when users do not click on the crop button again; it results in overwriting the existing file ...

What is the best way to send my webform data to a web API controller as a model class using JQuery AJAX?

This is the AJAX code I have written to pass two values to my API: function submitData() { var username = $("#username").val(); var password = $("#password").val(); $.ajax({ type: 'POST', ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Displaying data labels overlaid on top of data points in line charts

Currently, I am utilizing Angular2 along with ng2-charts to generate a line chart. My objective is to position the data labels directly above the points, similar to how they appear in the bar chart showcased in this image: bar chart I stumbled upon the ch ...

How to integrate external JavaScript files with Angular CLI and Webpack

I'm facing a challenge on how to incorporate JS files (vendors) after transitioning Angular Cli from SystemJs to Webpack. For instance Option A I have npm-installed js files. Simply adding script tags to the head tag doesn't work, and it doesn ...

Steps for incorporating a filter feature in an Angular Material table

.HTML: Can someone assist me with implementing a filter in this component? I tried using it with the expansion table, but unfortunately, the filter is not working as expected. <mat-dialog-content style="width: 63rem; overflow: initial;"&g ...

Obtain information from Firebase and display it in a list

I've been struggling to retrieve my to-do tasks from a firebase database, but unfortunately, no data is appearing on my view. Surprisingly, there are no errors showing up in the console. My journey led me to the point of "saving data" in firebase. H ...

Angular encountering a null value within a pre-existing nested object

Upon receiving a fully populated object from my server to my angular service, everything appears correct in Postman and when I use JSON.stringify in the Angular component. However, I encounter an issue when trying to access nested objects within the view. ...

Learn how to automatically update data in Vue JS after making a 'POST,' 'DELETE,' or 'PUT' request in Vue JS 2

Whenever I send a 'POST' or 'DELETE' request, the data doesn't update automatically. I have to manually reload the page to see the updated information. Is there an easy way to refresh the data after making any 'POST' / &a ...

Using Vue: Save user information in the Vuex store prior to registration

Hello fellow members of the Stackoverflow Community, I am currently working on a Vue.js application that involves user registration. The registration process is divided into three components: Register 1 (email, password), Register 2 (personal information) ...

Exploring Angular 1.5: A guide to binding a transcluded template to a component's scope

Currently, I am utilizing a form component that includes common validation and saving functions. Inputs are injected into the form as transcluded templates in the following manner: <form-editor entity="vm.entity"> <input ng-model="vm.dirt ...

Is it possible to track keystrokes without the use of text input fields?

For various unimportant reasons, I need to use JavaScript to create links instead of using the anchor tag. I want the behavior to mimic the anchor tag, allowing users to open a link in a new tab when holding down the Ctrl key or in a new window when holdin ...

Exploring the process of extracting/parsing HTML with Microdata

Hello, I am relatively new to the concept of Microdata. I currently have an HTML string that contains Microdata and I am interested in exploring the possibility of extracting the necessary information dynamically using Microdata with JavaScript or jQuery. ...

Steps for converting an Array of tuples into a Union of Tuples

I am attempting to develop a custom type that, when given an array of tuples as input, will generate the union of each index within the tuple. This may not be the most accurate terminology, but I hope you understand what I mean. const entries = [["name", ...

Steps for declaring CSS values with fallbacks in case of unsupported values

I'm looking to utilize the overflow: overlay property in Chrome, and overflow: scroll in Firefox. Simply declaring the overlay value causes Firefox not to scroll at all, even though I know it's not standard. My question is: what's the optim ...