What is the best way to retrieve form input and select values using Angular Binding?

Just starting out with angular2, so please be patient with me. I realize this might be a beginner's question for some.

<form>
  <label class="input-group">
    <p>View By</p>
    <select [(ngModel)]="balance.viewBy" name="viewBy">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </label>
  <label class="input-group">
    <p>Date From</p>
    <input [(ngModel)]="balance.dateFrom" name="dateFrom"/>
  </label>
  <label class="input-group">
    <p>Date To</p>
    <input [(ngModel)]="balance.dateTo" name="dateTo"/>
  </label>
  <button type="button" (click)="search_data_balance()">Search</button>
</form>

component.ts

export class BalanceComponent {
    search_data_balance(){
        // retrieve all input values here.
    }
}

Here is what I have attempted:

let vb = balance.viewBy,
  df = balance.dateFrom,
  dt = balance.dateTo;

// encountered an error

In angular1, we could access these values using $scope.

Any assistance on this would be greatly appreciated. Thank you.

Answer №1

balance.viewBy will store the selected value.

The value attribute (for strings) or ngValue attribute (for other types) must be defined.

  <option [ngValue]="1">1</option>
  <option [ngValue]="2">2</option>
  <option [ngValue]="3">3</option>
  <option [ngValue]="4">4</option>
  <option [ngValue]="5">5</option>

Answer №2

Are you attempting to connect various controls to different properties of a model object within your component?

Your model object needs to be present in your component as a property that is initialized. In order to access the values, you will need to reference that property object like this:

export class BalanceComponent {

    private balance = {}; // <----  

    search_data_balance(){
        console.log(this.balance.dateTo);  // <----
    }

}

Answer №3

If you need to adjust your code, consider removing the balance variable as it may not be compatible with angular2.

<select [(ngModel)]="viewBy" name="viewBy">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

<button type="button" (click)="search_data_balance(viewBy)">Search</button>

To properly handle data in your component, make sure to define each model within the class.

export class BalanceComponent {
    viewBy: any;   // definition
    viewBy = 1;    // default value

    search_data_balance(view){
        console.log(view);    
    }
}

Edit 2:

// Pass the balance object as an argument in the function to access it within the class component

<button type="button" (click)="search_data_balance(balance)">Search</button>

Component

export class BalanceComponent {
    // Defining balance in the component
    // Default value is set to 1.
    private balance = {
        viewBy: 1
    };

    search_data_balance(balance){
        console.log(balance);
        console.log(balance.viewBy); // Displaying the viewBy value
    }
}

Hope this solution works for you. Cheers!

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

Expanding the interactive capabilities of a stateful component with connections

I am looking to design a foundational Redux component with its own state and properties. As I extend it in a generic fashion, I aim to combine the properties and state of the extended object with the base. It is crucial for this component to be linked with ...

Struggling to get SVG and <p> elements to align on the same line using display:inline-block?

Alright, I'm struggling to align this HTML content properly. The generated code looks like: <div id = "innerCal"> <div id = "calCell"><p>[</p> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 447 443"><defs>< ...

Switching from Ldapsearch to ldapjs transformation

I've been experimenting with converting a ldapsearch query from ldapsearch to an ldapjs script: ldapsearch -H ldap://ldap.berkeley.edu -x -b 'ou=people,dc=berkeley,dc=edu' objectclass=* Here is the ldapjs script I have been working on: va ...

"Utilize the UpdateOne function in MongoDB to add a value from a different field

Attempting to add an existing field of my document to an array. Here is the schema: const mySchema = new Schema({ level: { type: Number, default: 1 }, mHierarchy: [ { userId: { type: mongoose. ...

When working with NextJs and MikroORM, encountering the error "Cannot use import statement outside a module

Resolving SyntaxError When Integrating MikroORM with NextJS Challenge Encountered While attempting to incorporate MikroORM v6.3.13 into a NextJS v14.2.14 project, I encountered a critical issue. At this point, my primary goal is to establish the setup cor ...

Mastering the art of properly connecting Angular HttpPromise

Recently, I encountered an angular Service containing a crucial function: service.getItemByID = function(id) { var hp = $http({method: "GET", url: "service/open/item/id", headers: {"token": $rootScope.user.token}, para ...

Securing ASP.NET Web API with Cross-Domain AJAX Requests: A Comprehensive Guide

I am in the process of developing an API on www.MyDomain.com that needs to be accessible from public websites such as www.Customer1.com and www.Customer2.com. These websites are designed to showcase each customer's inventory without requiring users to ...

The object continues to be undefined despite its placement in a global scope

Currently, I am working on building a game of pong and encountering an issue with creating a paddle in the initialize method. Despite storing it as a global variable, the paddle remains undefined. I even tried making it a property of 'window', bu ...

How can I retrieve information from PHP using json_encode and access it in JavaScript?

Currently in the process of developing a web app using Phonegap and XUI. Fetching data from an external domain through an http request with XUI. The retrieval process is successful, as I am able to receive JSON data in the following format: ({"first":"J ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

Tips on how to render a component only after receiving an AJAX response

I'm encountering an issue with one of my React components. It seems like AJAX is not fetching all the content from the external server before React renders the ChildComp component. https://i.stack.imgur.com/o0ZtH.png Above, you can view the tree of ...

Error: The Rollup module is unable to locate the 'jquery' file

I've been facing an issue while trying to bundle a vuejs single file component using rollup. The error message that keeps popping up is Module not found: Error: Can't resolve 'jquery'. Despite spending countless hours on this problem, I ...

Exploring the concept of global objects within the expressjs framework

Currently, I am working on building a school management system. One issue I encountered is related to the creation of global objects in my backend when a teacher sends a post request. I am wondering whether multiple teachers accessing the server will res ...

Having trouble getting my ReactJS page to load properly

I am currently linked to my server using the command npm install -g http-server in my terminal, and everything seems to be working smoothly. I just want to confirm if my h1 tag is functional so that I can proceed with creating a practice website. I have a ...

Designing a personalized Angular package for components

I am currently working on developing reusable components that can be utilized across multiple teams. After creating a new Angular project, I went ahead and published it to Azure DevOps artifacts. When attempting to use the component in another project, I ...

Unable to pass data from a Jquery ajax request to another function

I've written a basic ajax request using jQuery. Here is the code for my ajax function: var sendJqueryAjaxRequest = function(arrParams) { var request = $.ajax({ url: arrParams['url'], async: false, ...

Transform socket.on into a promise

Currently, I am developing a service that involves the function init acting as resolve. Initially, it generates a folder using the connection's id and then proceeds to write some default files inside this newly created folder. The main goal here is to ...

Npm Installation Issue (Dependency Resolution Failure)

Whenever I attempt to execute npm install, I encounter the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

React: The useContext hook does not accurately reflect the current state

I'm currently facing a dilemma as I attempt to unify data in my app. Whenever I click the button, the isDisplay value is supposed to be set to true; even though the state changes in my context file, it does not reflect in the app. Thank you for your ...

When the "ok" button is clicked in a custom confirmation box, the function will return

When the first button is clicked, I validate certain text boxes and then call Confirm() to display a confirmation box. I want it to return true to the calling function when "ok" is clicked and for control to go back to the UI to proceed ...