Access NgModel from NgForm

Is there a way to access the NgModel of a FormControl retrieved from the NgForm.controls object within its parent form, or directly from the form itself?

Upon form submission, I pass the form as a parameter to a custom function:

<form #myForm="ngForm" name="myForm" (ngSubmit)="myFunc(myForm)">
  <input type="text" name="myInput" ngModel #myInput="ngModel">
</form>

myFunc(form) {
  form.controls // Retrieves {[key: string]: FormControl}
}

I aim to modify properties of the controls fetched from the form (as NgModels) and use them in the template like this:

{{ myInput.myProp }}

Rather than:

{{ myInput.control.myProp }}

The main objective is to assign a custom property to each NgModel in a form upon submission, without having to extract that property from its underlying control. Is this achievable or am I approaching it incorrectly?

Answer №1

Give this a shot:

<form #customForm="ngForm" name="customForm" (ngSubmit)="submitForm(customForm)">
  <input type="text" name="customInput" ngModel #customInp="ngModel">
  {{ customInp.value }}
</form>

Answer №2

When you use #myInput="ngModel", you are assigning an ngModel to #myInp in order to access the native element.

<form #myForm="ngForm" name="myForm" (ngSubmit)="myFunc(myForm)">
  <input #myInp type="text" name="myInput" ngModel #myInput="ngModel">
  {{myInp.getAttribute("my-attr")}}
</form>

To set a custom attribute value, follow this approach:

@ViewChild("myInp") myInput: ElementRef;
myFunc(form) { 
    this.myInput.nativeElement.setAttribute('my-attr', 'attr: ' + form.value.myInput);
}

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

Changing the way in which text is selected and copied from a webpage with visible white space modifications

After working on developing an HTML parser and formatter, I have implemented a new feature that allows whitespace to be rendered visible by replacing spaces with middle dot (·) characters and adding arrows for tabs and newlines. https://i.sstatic.net/qW8 ...

Angular Route seems unreachable

These are my guidelines for routes: export const appRoutes: Routes = [ { path: "", component: HomeComponent }, { path: '/signup', component: AppComponent }, { path: "**", redirectTo: "/" } ]; Upon attempting to access the URL: http ...

Acquiring information from a Service and saving it in a Child component - Angular version 11

Utilizing my service, I fetch API data for the child component. Initially, it retrieves the Id and other user data, displaying it in the console. ngOnInit(): void { this.commonService.userSetChange.subscribe( apiData => { this.getUserS ...

What is causing the error message to appear even though the element has been correctly defined? - TypeError: Unable to access the value property of null

Objective: Obtain the value of an HTML element in TypeScript (Angular) Issue: Error: Uncaught (in promise): TypeError: Cannot read property 'value' of null Error Message: TypeError: Cannot read property 'value' of null at UserRegi ...

Utilizing TypeScript with React to dynamically select which component to render

My task seemed simple at first: to render a React component based on its name/type. Here is an example of how it is used: // WidgetsContainer.ts // components have a difference in props shape! const componentsData = [ { type: 'WIDGET_1', ...

What is the best way to access data in a node.js application from IONIC typescript via a REST API?

Here is the structure of my service.ts: import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/http'; import 'rxjs/add/operator/map'; /* Generated class for the PeopleSearch provider. See http ...

Is your React Native list elements feeling a little too close for comfort?

I'm facing an issue where the items in my list are not properly spaced out and I'm unable to figure out why. I have 3 elements for each letter that should be separated from each other. I suspect that the issue might be related to the fact that th ...

Retrieving the status of a checkbox using Angular's field binding feature

While using Angular 5.1.1, I am facing an issue where a function is not called correctly when a checkbox changes. This problem seems to occur specifically with the checkbox input type, as it always sends the value "on" to the function even when the checkbo ...

How can I adjust the padding and width attributes of the mat-menu in Angular 5

Today, I am struggling with a piece of code. Whenever I click on the Details button, it is supposed to open a mat-menu. However, for some reason, I cannot seem to adjust the padding or width of the menu: <div id="box-upload" [hidden]="hiddenBoxUpload" ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

When attempting to publish an index.d.ts file using npm, the module is

We are currently in the process of developing an npm package that will serve as the foundation for most of our projects. However, we have encountered some issues that need to be addressed: The index.d.ts file of our base npm package is structured as shown ...

BehaviorSubject does not retain duplicate entries in the array

When adding values to a service and component, the first value in the array changes to the second value. Here is an overview of the code: Service export class PrepayService { private _carts: BehaviorSubject<ShoppingCart[]>; carts : Observable ...

What purposes do the different files within an Angular bundle serve during AoT compilation?

After running the command ng build --prod --aot in my Angular 4 project, I found the following files in my dist folder. inline.6405cab307cfc3c6a636.bundle.js : 2 KB main.a799c9fd4322567743dc.bundle.js : 35 KB polyfills.b72d4efc376613f94934.bu ...

Fixing the 401 (Unauthorized) error when attempting to log in

I keep encountering a 401 error when trying to log in with JWT authentication. Strangely, the signup page works perfectly fine and successfully adds the user to the database. However, for some reason, the login functionality is not working. I'm unsure ...

What is the best way to display the output of a Set-typed function using a class key in my code?

I'm currently working on developing a function that can return a Set containing the keys of a class. However, I am struggling to determine the correct definition for this function. class Bot { public no01: number; public no02: number; construct ...

How can I search multiple columns in Supabase using JavaScript for full text search functionality?

I've experimented with various symbols in an attempt to separate columns, such as ||, |, &&, and & with different spacing variations. For example .textSearch("username, title, description", "..."); .textSearch("username|title|description", "..."); U ...

Create an array variable for services in Angular

My goal is to define this user as an array. users = new BehaviorSubject<any>([]); In my component, I am attempting to add the userID to the array. this.Service.users.push(userID); To subscribe to it, I use the following code: this.Service.users.su ...

What is the best method for transforming an object into an interface without prior knowledge of the keys

I am looking for a solution to convert a JSON into a TypeScript object. Here is an example of the JSON data: { "key1": { "a": "b" }, "key2": { "a": "c" } } The keys key1 and key2 a ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...

Issue: The function (0, react__WEBPACK_IMPORTED_MODULE_1__.useActionState) is not recognized as a valid function or its output is not iterable

I found a great example of using useActionState at this source. Currently, I am implementing it in my project with Next.js and TypeScript. app/page.tsx: "use client"; import { useActionState } from "react"; import { createUser } from ...