Obtaining the identification of an element from a FormControl

Hello, I have an input selection with a label (value) and key (id). When I click on submit, I want to retrieve the key (id).

<form (submit)="onSubmit(testForm)" [formGroup]="form">

<mat-form-field>
  <input matInput type="text" name="user" [formControlName]="username" id="userid" required>
</mat-form-field>

<button mat-raised-button color="primary" type="submit">submit</button>
</form>

//I anticipate getting the [id] value from form.controls.username ... id

Answer №1

It is recommended to utilize property binding for the [value] attribute and ensure that a key is set.

Avoid using required as it works more effectively with template-driven forms, instead use Validators.required.

Additionally, opt for (ngSubmit) over (submit).

Explore the documentation on reactive forms

<form (ngSubmit)="onSubmit()" [formGroup]="form">
  <input
    matInput
    type="text"
    name="user"
    formControlName="username"
    id="userid"
  />
  <mat-form-field>
    <mat-label>Favorite food</mat-label>
    <mat-select formControlName="food">
      @for (food of foods; track food) {
      <mat-option [value]="food.value">{{food.viewValue}}</mat-option>
      }
    </mat-select>
  </mat-form-field>
  <button mat-raised-button color="primary" type="submit">submit</button>
</form>

TS:

import { Component } from '@angular/core';
import {
  ReactiveFormsModule,
  FormGroup,
  FormControl,
  Validators,
} from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';

interface Food {
  value: string;
  viewValue: string;
}

/**
 * @title Basic select
 */
@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  standalone: true,
  imports: [
    MatFormFieldModule,
    MatSelectModule,
    MatInputModule,
    ReactiveFormsModule,
  ],
})
export class SelectOverviewExample {
  form = new FormGroup({
    food: new FormControl('', Validators.required),
    username: new FormControl('', Validators.required),
  });
  foods: Food[] = [
    { value: 'steak-0', viewValue: 'Steak' },
    { value: 'pizza-1', viewValue: 'Pizza' },
    { value: 'tacos-2', viewValue: 'Tacos' },
  ];

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

Check out the Stackblitz 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

Discover the myriad of possibilities created by combining arrays

I am working on a code snippet that aims to generate an array containing all possible combinations between two or more arrays. However, I am encountering a specific issue. getCombn(arr: string | any[], pre?: string | undefined) { pre = pre || ' &a ...

Validation in PHP and Javascript is only partially effective

I encountered an issue with my form validation setup that utilizes JavaScript, Ajax, and PHP. While the errors are correctly displayed when the form is filled incorrectly, I am unable to submit the form even if there are no errors. Clicking the submit butt ...

Ensuring maximum length validation on input

I am having an issue with the function "checkNumbers()". I am attempting to validate if my input does not exceed 10 numbers; while "isAllowedSymbol()" is functioning correctly, the other one is not. What could be causing this problem? function isAllowe ...

Utilizing Laravel to Send Table Data to Modal for Form Submission to Controller

In our users table, there is an edit modal that needs to retrieve specific user data from the table list and display it within the modal's input fields. This requires using Laravel logic to edit the data and submit it back to the controller as a form. ...

Please ensure you have selected at least one item before submitting the form

I have been working on validating a form using a combination of bootstrap and angularjs. The form includes two groups of checkboxes that need to be validated. It is required for the user to select at least one checkbox from each group in order for the Subm ...

The access to the HTTP request has been restricted

Currently, I am developing multiple applications that need to communicate with each other. To test these apps, I am using both Chrome and Firefox browsers. Strangely, the issue persists in both browsers. The issue at hand: In one of my applications (let& ...

ReserveYourSpot: Effortless Seat Reservation with AngularJS at the Click of a Button [GIF]

ReserveYourSpot: An innovative AngularJS application designed to streamline the process of reserving seats for a movie show, similar to popular platforms like BookMyShow. https://i.stack.imgur.com/PZk1I.gif Interactive User Functions (Use Cases): A ...

What is the best way to set a specific maximum size for the dropdown selector in Material UI's TextField component?

Working on a Sign up Page involves prompting users to select their location from a dropdown list of different countries. However, the issue arises when the dropdown list covers the entire screen, making it difficult for users to navigate. Is there a way to ...

Utilizing jQuery Supersized: Techniques for Implementing an Array Derived from a List Item

Hey there, I recently started using the Jquery Supersized plugin and wanted to find a better way to create a list of images. I came across a similar question on Stack Overflow jQuery Supersized: Load images from LI, but I'm struggling to implement the ...

"Enhance your user experience with Abp.io Commercial's Identity Module Localization

I've been struggling to locate proper documentation on how to change the identity module's Name and Surname fields to First Name and Last Name in a UI with Angular. We did not purchase the source code for ABP.io commercial. I've attempted va ...

Enhance object position by utilizing Dragula and Angular 5 through dropping action

I have a bag divided into different sections, each containing items with a specific location value. For example, the "Misc" section has items with "location: misc," the "Armor" section has items with "location: armor," and so on. While I can sort the item ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

What is the best way to ensure all Promises are resolved in ExpressJS?

Context: I've developed a basic REST API in ExpressJS that enables the seamless integration of multiple web pages. The page numbers are flexible and can vary. Challenge: Due to constraints related to performance, I am keen on incorporating async pr ...

Tips for generating an about:blank webpage featuring a personalized iframe

I'm attempting to create a form with the following functionality: Enter a URL into a text box. Click a button and it opens an about:blank page in a new tab. The opened page contains an iframe that occupies the entire screen, with the src attribute se ...

Iterate through a JavaScript object while simultaneously executing asynchronous calls

My goal is to use the THREE.XHRLoader to load multiple files, then add the key of each loaded object along with the file to another object called loadedFiles. The issue I'm facing is that when trying to retrieve the key for each loaded object, it alwa ...

Looking to target an element using a cssSelector. What is the best way to achieve this?

Below are the CSS Selector codes I am using: driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg-technik='append_numbers']")).click(); driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg- ...

Using WebdriverIO with Angular to create end-to-end tests in TypeScript that involve importing classes leads to an error stating "Cannot use import statement outside a module."

I am facing an issue while trying to set up a suite of end-to-end tests using wdio. Some of the tests utilize utility classes written in TypeScript. During the compilation of the test, I encountered the following error: Spec file(s): D:\TEMP\xx& ...

JavaScript GridView

Is there a way to determine if an ASP.NET GridView contains at least one row by using JavaScript? ...

Sending information to Firebase using Angular 4

Utilizing Angular 4 in combination with AngularFire, I have successfully implemented a data transfer to Firebase. The specific data that I am looking to retrieve includes: name, country, zip-code paired with email and password details. Following the upda ...

Converting a <select> element with optgroup into a JSON array: A step-by-step guide

HTML: <select multiple size="10" class="show" id="boxA"></select> <nav id="buttons"> <ul class="small-block-grid-2 medium-block-grid-2 large-block-grid-2"> <li><a class="remove" href="#">Remove</a>< ...