What could be causing my form to malfunction when sending? Comparing [(ngModel)] to form submission in Angular 2+

I recently made changes to the form implementation on my login screen. Instead of binding to the inputs [(ngModel)] in the backend, I now pass the form itself.

Although this change allowed the original tests to pass, it caused issues with the actual app functionality. Can anyone help me understand what went wrong here? Please note that the code provided is just a simplified example.

BEFORE


app.ts

username: string;

onSubmit(form: NgForm) {
  if (form.valid) {
    // do something with this.username...

    // this.username will reflect whatever is entered in the input box since it is bound with [(ngModel)]
  }
}

app.html

<input class="form-control" id="username" name="username" type="text" autofocus required
             placeholder="username" [(ngModel)]="username"/>

After


app.ts

username: string;

onSubmit(form: NgForm) {
  this.username = form.value.username
  if (form.valid) {
    // do something with this.username...

    // this.username should now hold the value passed via the form
  }
}

app.html no longer includes [(ngModel)]="username"

<input class="form-control" id="username" name="username" type="text" autofocus required
             placeholder="username"/>

Answer №1

To ensure your input has a binding, consider using reactive forms:

app.ts

import {FormControl} from "@angular/forms";

...
usernameCtrl = new FormControl();

onSubmit()
{
    if(this.usernameCtrl.valid)
    {
        // perform an action
    }
}

app.html

<input ... [formControl]="usernameCtrl" />

Edit

Understanding the difference between NgModel & NgControl: Difference between using ng-model and ng-control in angular2?

In that discussion, they mentioned:

Controls are responsible for providing information about the form or a specific input's state (valid, pristine, touched, etc.). They are commonly used to display validation errors.

If you have more than one input, consider using FormGroup instead of FormControl:

app.ts

import {FormBuilder, FormGroup} from "@angular/forms";
...
//decorator
export class SomeClass implements OnInit
{
public reactiveForm = new FormGroup();

constructor(private fb: FormBuilder){}

public ngOnInit()
{
this.reactiveForm = this.fb.group({username: [""]});
}

public onSubmit()
{
if(this.reactiveForm.valid)
{
const raw = this.reactiveForm.getRawValue(); //output -> { username: "blabla"}
// handle raw data accordingly
}
}
}

app.html

<form [formGroup]="reactiveForm">
<input ... formControlName="usernameCtrl" name="usernameCtrl"/>    
<button [disabled]="!reactiveForm.valid">Submit</button>
</form>

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

What is the best way to store the data in the lowest common ancestor for effective communication among multiple identical components within a sibling network?

My Background: I have expertise in Python and Vue development, with a history of using Vue dating back to 2016. One of my clients operates a business focused on weight loss and meal planning: clients pay her for weekly single-page PDF menus that outline t ...

displaying solely the bottom two rows while concealing the remainder

Looking for a Google Docs script that can automatically display only the last two rows in a spreadsheet. The goal is to have the new data added in a row and when ENTER is pressed, it will show only the latest two rows while hiding all others. I've st ...

Utilize CSS properties to pass as arguments to a JavaScript function

Is there a way for me to make my CSS animation functions more efficient? I have similar functions for different properties like height, width, and left. Can I modify the function below to accept a CSS property argument instead of hardcoding height? Window ...

The texture of various shapes in ThreeJS isn't functioning as expected

I have been experimenting with dynamic textures on threejs and I've noticed that when using different shapes, the texture does not work as expected. However, when I use boxGeometry, everything seems to be working perfectly. setCanvas =()=>{ th ...

The directive does not have the "exportAs" property configured to "ngbDatepicker"

When working with Angular 4, I attempted to integrate a datepicker into my project using the datepicker-popup.html file. However, I encountered an error that has left me puzzled. Can someone please provide assistance in identifying and resolving this issue ...

Even when it appears to be chaotic, the TypeScript array of numbers always manages to find its way back to being sorted

I recently developed a function that aims to verify if an array of numbers is sorted: const checkIfSorted = (numbers: number[]) => { return numbers === numbers.sort((a, b) => a - b); }; checkIfSorted([4, 2, 8, 7, 3, 10, 1, 5, 9, 6]); // This cur ...

What exactly does this look like a form of initializing a JavaScript array and for what purpose?

Currently, I am attempting to work through a JavaScript (Node.js) example that involves saving data to a MongoDB database store. Within the code snippet provided below, there is a part that has left me puzzled. Despite my efforts, I cannot seem to grasp t ...

Utilizing a monorepo approach enables the inclusion of all *.d.ts files

Scenario: In our monorepo, we have 2 workspaces: foo and bar. foo contains the following files: src/file.ts src/@types/baz.d.ts The bar workspace is importing @monorepo/foo/src/file. While type-checking works for the foo workspace, it does not work fo ...

Is it better to keep a lengthy array in the back-end or front-end storage?

I'm facing a dilemma in my angular application. I have a lengthy array that I need to access easily from the front-end without causing any slowdowns. There are various options available, but I'm unsure which one would be the most efficient. Shoul ...

What is the most effective method for exchanging variables between programs or threads?

I currently have a program that executes an algorithm processing real-time data. Once per hour, the algorithm's parameters are optimized based on new historical data. Currently, this optimization process is running in a single thread, pausing the rea ...

Turn off slider trace animation?

Check out the slider component in MUI here: https://mui.com/material-ui/react-slider/ I'm currently exploring how to disable the animation on the nub so it moves instantly to the new position. Any advice on how to achieve this? ...

Error encountered with NextJS and useRouter due to TypeScript - The type 'undefined' is invalid for use as an index

I'm facing a TypeScript error that I can't seem to resolve, despite trying solutions from other questions. It's giving me the error message 'Type 'undefined' cannot be used as an index type.' Type 'undefined' ...

What is the reason behind the array.push() method not altering the array?

Here's the challenge: Eliminate all falsy values from a given array. Falsy values in JavaScript include false, null, 0, "", undefined, and NaN. Tips: Try converting each value to a Boolean. Below is my attempt at solving it: function bouncer(a ...

I'm having trouble opening a new Angular project even though both my Node.js and npm are up to date. Can anyone help me

Just starting my Angular journey. I have successfully installed the latest version of node.js with npm and then added Angular CLI to it. All good until I typed this command in the node.js prompt: ng new my-app But now I'm stuck here! Any ideas on wh ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

What is the best way to prevent users from clearing the value attribute of an input element?

Sample Scenario: While a user is entering information into a field, I would like to restrict the ability to delete or clear out the value, such as keeping "Friend" intact. Can this be accomplished using CSS or JavaScript? ...

Disabling hammer.js touch events with the onclick event

I have recently completed constructing a carousel slider with touch events for a website project. I am currently trying to find a way to deactivate the touch events (hammer) using click events. Below is the code snippet that I have been working on: The cl ...

Using React to manage elements with duplicate refs

Can someone help me with this issue I'm facing? let list = storage.map((element, index, array) => { return ( <li key={index} className="list-element"> <div className="title-wrapper" onMouseEnter={this.handleMouseEnter}> ...

Prevent any angular text box from allowing just one special character

Hello, I am facing a requirement where I need to restrict users from inputting only one special character, which is ~. Below is the code snippet: <div class="form-input "> <input class="pass" [type]="'passw ...

Using HTML and JavaScript to automatically update one input date based on changes made to another

Currently, I am developing an Angular application and encountered a challenge with two date input fields: <div class="col-lg-3"> <div> {{ dataInizioLabel }} </div> <input required type="datetime-local" ...