Accessing several values in Angular by clicking

I have a dropdown that contains an input field and two more dropdowns. I am looking for a way to retrieve the values of all three fields when the search button is clicked.

Screenshot

https://i.sstatic.net/5Imaq.png

Code

HTML

<nz-dropdown-menu #menu="nzDropdownMenu">
    <div class="card search-box p-2">
        <div class="mb-2">
            <label for="">Search By {{ column.name }}</label> <br>
            <input nz-input placeholder="Type here..." />
        </div>

        <div class="mb-2">
            <label for="sort">Sort Order</label> <br>
            <nz-select ngModel="none" class="text-left mr-2" style="width:100%;">
                <nz-option nzValue="none" nzLabel="None"></nz-option>
                <nz-option nzValue="asc" nzLabel="Ascending"></nz-option>
                <nz-option nzValue="desc" nzLabel="Descending"></nz-option>
            </nz-select>
        </div>

        <div class="mb-2">
            <label for="op">Filter Column</label> <br>
            <nz-select ngModel="contains" class="text-left mr-2" style="width:100%;">
                <nz-option nzValue="contains" nzLabel="Contains"></nz-option>
                <nz-option nzValue="like" nzLabel="Like"></nz-option>
            </nz-select>
        </div>
        
        <button type="button" class="btn btn-warning w-100 mt-2" (click)="search()"><i class="fe fe-search"></i> Search</button>
    </div>
</nz-dropdown-menu>

Component

search(): void {
   // Code to retrieve values will go here
}

Answer №1

By utilizing ReactiveForms, you have the ability to access form values as required

RETRIEVING FORM DATA USING REACTIVEFORMMODULE :-

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule ,ErrorHandler } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
declarations: [],
imports: [ FormsModule,ReactiveFormsModule]});

export class AppModule { }

COMPONENT.TS

import { Component,OnInit } from '@angular/core';
import {FormGroup,FormControl,Validators,FormArray} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
.
.
.
public formName: FormGroup;
constructor(private formsModule: FormsModule) {
 this.formName =  this.formBuilder.group({
   firstName:  [null, Validators.required],
   lastName:  [null, Validators.required],
 })
} 

 onSubmit() {
   console.log(this.formName.value);
 }

COMPONENT.HTML

<form [formGroup]="formName" (ngSubmit)="onSubmit()">
   <div>
     <input type="number" formControlName="firstName">
   </div>
   <div>
     <input type="number" formControlName="lastName">
   </div>
  <button class="btn btn-primary" type="submit">Submit</button> 
</form>

OUTPUT in CONSOLE

{firstName : ... , lastName : ...}

Expecting this to be useful for everyone!

Answer №2

To implement form controls in Angular, you can utilize the built-in features provided by the framework. Here's an example of how you can use form controls within your Angular component:

 <nz-dropdown-menu #menu="nzDropdownMenu">
    <div class="card search-box p-2">
      <div class="mb-2">
        <label for="">Search By {{ column.name }}</label> <br>
        <input nz-input placeholder="Type here..." formControl="searchControl"/>
      </div>

      <div class="mb-2">
        <label for="sort">Sort Order</label> <br>
        <nz-select ngModel="none" class="text-left mr-2" style="width:100%;" formControl="orderControl">
            <nz-option nzValue="none" nzLabel="None"></nz-option>
            <nz-option nzValue="asc" nzLabel="Ascending"></nz-option>
            <nz-option nzValue="desc" nzLabel="Descending"></nz-option>
        </nz-select>
      </div>

      <div class="mb-2">
        <label for="op">Filter Column</label> <br>
        <nz-select ngModel="contains" class="text-left mr-2" style="width:100%;" formControl="filterControl">
            <nz-option nzValue="contains" nzLabel="Contains"></nz-option>
            <nz-option nzValue="like" nzLabel="Like"></nz-option>
        </nz-select>
      </div>
      <button type="button" class="btn btn-warning w-100 mt-2" (click)="search()"><i class="fe fe-search"></i> Search</button>
    </div>
</nz-dropdown-menu>

In your component.ts file, you would define the form controls like this:


import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

constructor() {} 
searchControl: FormControl = new FormControl();
filterControl: FormControl = new FormControl();
orderControl: FormControl = new FormControl();

 search() {
    console.log(searchControl.value);
 }

Alternatively, you have the option to use ngModel or form groups depending on your requirements.


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

"Threads snap as soon as they begin to be put to use

Encountering an issue with the command yarn run serve, the error log states: $ vue-cli-service serve INFO Starting development server... 10% building 2/2 modules 0 activeevents.js:173 throw er; // Unhandled 'err ...

Is it possible to use a server action in Next.js to both retrieve data and refresh the page?

I am currently working on developing a web application using Next.js (13.4.9) and I intend to utilize server actions. These server actions will involve sending data to the server, which will process the data and return a string back to me. The challenge I& ...

Changing the Position of HTML Scripts in React

I am facing an issue where I need to relocate an external script within a specific section of my page. However, I am unable to access the CSS attributes associated with this item. It seems that it is displayed as an iFrame, making it difficult to modify th ...

Can you guide me on how to generate a personalized stamp within the Angular component using Grapecity GcPdfViewer?

When a Pdf is opened in the GcPdfViewer by the User, they are required to stamp the Pdf with an image located in the src/assets folder. However, the example provided on this webpage is not functioning correctly. Can anyone offer me a functioning example? ...

Suggestions for resolving this problem when attempting to add an item to an array

I am currently working on a form that allows users to add items into an array list. However, I am facing an issue where if a user chooses to add more devices into the array and changes the model type, the code counts it as part of the previous array if the ...

Warning in TypeScript when attempting to modify a single state property within a React component

Imagine we have a simple react Component: import React, { Component } from 'react'; interface IState { a: boolean; b: string; c: number; } class Test extends Component<{}, IState> { state = { a: true, b: 'value' ...

What could be causing the subscription in reactive form to not function properly?

Given the form is: this.filterForm = this.fb.group({ classNumber: [null, []], classSuffix: [null, []], teacher: [null, []], subject: [null, []] }); Attempting to assign a value to a field in the constructor of the class: this ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...

Typescript: Enhance your coding experience with intelligent parameter suggestions for functions

Within a nest.js service, there is a service method that takes an error code and generates a corresponding message to display to the user. The example below shows a simplified version of this method: getGenericErrorMessage(input: string): string { co ...

What is the procedure for submitting all checkbox values through Google Apps Script?

My web app created using Google Apps Script can generate a custom table of data for users to select for calculations. I use Google Sheets to populate the table with values and checkboxes, but note that the table size may vary depending on the user. <fo ...

Acquire information asynchronously in JavaScript while inside a for loop

Recently, I've been exploring this particular function snippet: function add_cnh(arr_clelem){ var id=arr_clelem.getElementsByClassName("present")[0].id; var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date'); v ...

Changing the border of an iframe element using jQuery or Javascript from within the iframe itself

Is it possible to set the border of an iframe to zero from within the iframe itself using JavaScript or jQuery? Any guidance on how this can be achieved would be greatly appreciated. Thank you! ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

Encountered an exception while trying to retrieve data with a successful status code of 200

Why is a very simple get() function entering the catch block even when the status code is 200? const { promisify } = require('util'); const { get, post, patch, del } = require('https'); //const [ getPm, postPm, patchPm, deletePm ] = [ ...

Leveraging image values for selecting an image from a collection and showcasing it (Javascript)

I have a collection of images that I want to enlarge upon clicking. Here is what I currently have: <div class="gallery"> <div> <img src="content/imggallery/img1.jpg" class="oldimg" value="0"> </div> ...

retrieving data from Redis with the help of Node.js

I'm having trouble with the code snippet below. Despite setting values for the left_label and right_label variables in Redis, they always seem to return as "true". I suspect this is due to the client.get function returning true when successful. How ca ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

Having difficulties executing the npm command to install @ionic/cli-plugin-angular@latest with --save-dev and --save-exact flags on Ionic version 3.2.0

I am in the process of setting up a new project and I am using: ionic version 3.2.0 Cordova CLI: 8.0.0 Node 12.13.1 (lts) Running on Windows 10 When attempting to add a platform with the command ionic cordova platform add <a href="/cdn-cgi/l/email-pro ...

Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of http://localhost:3000/test/users/[id]. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb. My intention within the file a ...

Target only the <a> elements within a specific <div> using JavaScript

How can I target the first occurrence of the letter 'a' in this code using JavaScript? (href=some.php) <div class="accordionButton"><div id="acr_btn_title"><a href="some.php"><p>stuff</p></a></div><di ...