In Angular, providing a value in a form may not always hold true to its actual worth

Having an issue where the value passed from TypeScript to an input element is displayed on the screen, but the ngForm parameters show that the value is empty and the form is invalid.

Here is the HTML component:

<form #editForm="ngForm" (ngSubmit)="onSubmit(editForm)" novalidate autocomplete="off">
    <input type="text" name="sysid" id="sysid" readonly value="{{userList.sysid}}">
    <div class="form-group row">
            <label for="username">Username</label>
            <input type="text" class="form-control" id="username" placeholder="Enter username" name="username" #username="ngModel" ngModel required [class.invalid]="username.invalid" aria-describedby="unameErr" value="{{userList.username}}">
            <small *ngIf="username.invalid" id="unameErr" class="form-text">Username is Required</small>
        </div>
        <div class="col-sm-6">
            <label for="firstname">First Name</label>
            <input type="text" class="form-control" id="firstname" placeholder="Enter First Name" name="firstname" #firstname="ngModel" ngModel required [class.invalid]="firstname.invalid" aria-describedby="fnameErr" value="{{userList.firstname}}" oninput="this.value = this.value.toUpperCase()">
            <small *ngIf="firstname.invalid" id="fnameErr" class="form-text">First Name is Required</small>
        </div>
    </div>
    <input type="submit" class="btn btn-primary" value="Save" [disabled]="editForm.invalid">
</form>

This is my TypeScript code:

ngOnInit(): void {
    this.sub = this.route.params.subscribe(params => {
      this.formId = +params['formId']; // (+) converts string 'id' to a number
    });

    this.userList = {
      sysid: "",
      username: "",
      firstname: ""
    }

    this.getUserByIdnew(this.formId);
  }

 getUserByIdnew(formSysid: number) {
    this.apiservice.getUserbyIdnew(formSysid).subscribe((data: any) => {
      this.userList = {
        sysid: data.sysid,
        username: data.username,
        firstname: data.fname
      }
    })
  }

onSubmit(form: NgForm) {
    console.log(form);
  }

}

Upon submission, the console log displays:

https://i.sstatic.net/UJpqy.png

Despite values being displayed on the screen as shown in this image below:

https://i.sstatic.net/iAlQ3.png

Answer №1

A better practice is to avoid using the input value attribute in conjunction with ngModel. It is recommended to solely use the ngModel directive to bind the value.

 <form #editForm="ngForm" (ngSubmit)="onSubmit(editForm)" novalidate autocomplete="off">
        <input type="text" name="sysid" id="sysid" readonly value="{{userList.sysid}}">
        <div class="form-group row">
                <label for="username">Username</label>
                <input type="text" class="form-control" id="username" placeholder="Enter username" name="username" #username="ngModel" [ngModel]="userList.username" required [class.invalid]="username.invalid" aria-describedby="unameErr" >
                <small *ngIf="username.invalid" id="unameErr" class="form-text">Username is Required</small>
            </div>
            <div class="col-sm-6">
                <label for="firstname">First Name</label>
                <input type="text" class="form-control" id="firstname" placeholder="Enter First Name" name="firstname" #firstname="ngModel" [ngModel]="userList.firstname" required [class.invalid]="firstname.invalid" aria-describedby="fnameErr"  oninput="this.value = this.value.toUpperCase()">
                <small *ngIf="firstname.invalid" id="fnameErr" class="form-text">First Name is Required</small>
            </div>
        </div>
        <input type="submit" class="btn btn-primary" value="Save" [disabled]="editForm.invalid">
    </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

Issue encountered while running the 'yarn install' command in a React project: 'The system does not recognize the term 'yarn'

When attempting to run the 'yarn install' command in my React project, I'm running into a problem. Even though I have Yarn installed globally (npm install --global yarn), I keep getting an error when trying to use any Yarn command in the ter ...

Guide on implementing a FormArray within a FormGroup in the Angular 10 framework

I'm currently working on a form that includes regular inputs and an array of ingredients. While filling out the form, users should be able to add ingredients automatically. This is my first time using FormArray in creating a form and I've hit a ...

Issue with accessing class property in events.subscribe in Ionic3

I am currently working on a class that listens for events. When the event is triggered, I need to add the data that accompanies it to an array and then display it. Here's what my class looks like: export class customClass { dataArray:Array<stri ...

Guide on implementing dynamic rowspan in tables using vue.js

I am trying to create a table similar to the one in the example photo. https://i.sstatic.net/fkXDx.png I attempted to connect rows using rowspan and wrote some code for it, but unfortunately, I encountered an error in the browser. To start with, here is ...

Troubleshooting Issue with Angular Property Binding for Image Dimensions

Currently, I am exploring property binding in Angular through an example. The idea is to use an image and bind its width, height, and src attributes using property binding. Surprisingly, even though there are no errors and the image renders successfully vi ...

The validation touched event in Angular 5.2 seems to be malfunctioning

Here is an example of my input type: <input type="text" name="emaill" #emaill="ngModel" pattern="^\w+([\.-]?\w+)@\w+([\.-]?\w+)(\.\w{2,3})+$" [(ngModel)]="user.email" class="form-control input-underline" required ...

The Promise.then() function is not patient

Whenever I attempt to use Promise.then(), the events from this.events, this.tmEvents, and this.totalEvents keep logging before the promises are fully complete. Even when I tried implementing async/await to prevent this, I faced the same issue. Is there a ...

Separate the label and content sections in an Angular Material vertical stepper

https://i.sstatic.net/S1gIH.jpg After applying the following CSS: mat-step-header{ display: flex ; justify-content: flex-end ; } I am attempting to make this stepper function properly. I have implemented Angular Material design for a vertical stepp ...

Angular Typescript Controller's Constructor not being invoked

I have been working with Angular using TypeScript. Here is my model class in TypeScript: module app.form { export class Patient{ constructor( public firstName: string, public lastName: string, public gend ...

The ReactJS template with Typescript is throwing an error stating that the property useContext does not exist on type

After creating a react-app using yarn create react-app app-name --template typescript, I have the following code snippets to share: AuthProvider.tsx import { createContext, useState } from "react"; const AuthContext = createContext({ }); ex ...

Restrict and ignore associated field in typeorm

I need help in restricting the related data when querying using query builder. Here is the code I have for fetching employee orders: import { getRepository, Repository } from "typeorm"; public async findEmployeeQuery(id : number) { try { ...

What is the best way to create a multidimensional array with a fixed length in TypeScript?

I'm working on creating a 5x4 grid array in typescript and I'm struggling with properly instantiating it. When trying to push an element into the array using the method for a one-dimensional array, it's not working as expected and giving me ...

What is the proper way to define an array of objects in TypeScript?

In search of a way to define a function that accepts an array of unspecified object types, known as "anonymous types." I want to enforce strict typing with TypeScript. The objects in the array all have properties like name, price, and description. bagTotal ...

Utilizing a variable string name for a method in Typescript Vue

My objective is to trigger a different function based on the value of a variable. However, when working in VS Code, I receive an error message that states: 'method' implicitly has a type of 'any' because 'type1Func' and &apos ...

Refreshing a component in Angular/Angular2 using routerLink from the NavBar when already on the current route

When I am on the same route and click again from the navbar, nothing happens. Is there a way to refresh my component directly from the navbar using a method in routerLink? <li [routerLinkActive]="['active']"><a [routerLink]="['/ca ...

Using Angular CLI to send a post request to a local API but receiving a null response

After previously asking this question, I have managed to narrow down the potential errors and am now seeking assistance in a more specific manner. In my attempt to execute a post request to a local API within an angular app, I am consistently receiving a ...

A guide on showing an image from a JSON file path

As a beginner in Angular, I am currently working with Angular 8. I have a list of image paths stored in the 'dataSource' variable in JSON format, like so: hotdeals: Array(4) 0: {uri: "/Home/HotDeals/hotdeal1.png", id: "2"} 1: {uri: "/Ho ...

Calculating the total sum of an array utilizing filter and reduce techniques

How can I calculate the total value of all my products in the list by adding numbers together? this.totalValue = this.items.filter((item) => item.qtyvalue) .map((item) => item.qtyvalue) .reduce ...

The contents table remains fixed in the top right corner as you scroll

I have developed an Angular app with a table-of-contents component that only displays two items. The code for the script is as follows: ts import { Component, OnInit } from '@angular/core'; import { pdfDefaultOptions } from 'ngx-extended-p ...

Forming a distinct array from a collection of objects

Describing demoList: demoList = [ { id: 1, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 50, xxxN: 2.2, xxxQ45: 2, xxxQ100: 1.65, xxxQ125: null, xxxQ150: null, xxxQ2 ...