Unable to retrieve input value from form in Angular 8

There is a basic form on the HTML page that acts as an "Add-Edit" form. When opening the page with an ID, all inputs should be automatically filled with ObjectId values. If the page is opened without an ID, the inputs should be manually completed before adding the object to the database. The issue arises when trying to read or write values to the input fields using:

this.form.get["inputName"].setValue(value);

The console displays the error:

 Cannot read property 'setValue' of undefined

Below is the HTML code snippet:

<form [formGroup]="form" (ngSubmit)="save()" #formDir="ngForm" novalidate>
  <div class="form-group row">

    <mat-form-field>
      <input matInput [matDatepicker]="picker" placeholder="Choose a date" (dateInput)="addEvent($event)" (dateChange)="addEvent($event)" formControlName="picker">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>

    <div class="col-md-8">
      <label class=" control-label col-md-3">cost</label>
      <input class="form-control" type="text" formControlName="cost">
    </div>

    <label for="vehicles">Veicoli</label>
    <select formControlName="vehicleList" id="vehicleList">
      <option *ngFor="let vehicle of vehicles; let i = index" [value]="vehicles[i].id">
        {{vehicles[i].plate}}
      </option>
    </select>

    <label class=" control-label col-md-3">startKm</label>
    <div class="col-md-8">
      <input class="form-control" type="text" formControlName="startKm">
    </div>

    <label class=" control-label col-md-3">endKm</label>
    <div class="col-md-8">
      <input class="form-control" type="text" formControlName="endKm">
    </div>

    <label class=" control-label col-md-3">liter</label>
    <div class="col-md-8">
      <input class="form-control" type="text" formControlName="liter">
    </div>

    <label class=" control-label col-md-3">average</label>
    <div class="col-md-8">
      <input class="form-control" type="text" formControlName="average">
    </div>

  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-success float-right">Save</button>
    <button class="btn btn-secondary float-left" (click)="cancel()">Cancel</button>
  </div>
</form>

This section corresponds to the .ts file:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { FuelService } from '../services/fuel.service';
import { VehiclesService } from '../services/vehicles.service';
import { Fuel } from '../models/fuel';
import { Vehicle } from '../models/vehicle';
import { of } from 'rxjs';

@Component({
  selector: 'app-fuel-add-edit',
  templateUrl: './fuel-add-edit.component.html',
  styleUrls: ['./fuel-add-edit.component.css']
})
export class FuelAddEditComponent implements OnInit {

  form: FormGroup;
  plateCtrl: FormControl;
  actionType: string;
  fuelId: number;
  errorMessage: any;
  existingFuel: Fuel;
  vehicles: Vehicle[];
  dataSelected: Date;

  constructor(private fuelService: FuelService, private vehicleService: VehiclesService, private formBuilder: FormBuilder, private avRoute: ActivatedRoute, private router: Router) {
    const idParam = 'id';
    this.actionType = 'Add';
    if (this.avRoute.snapshot.params[idParam]) {
      this.fuelId = this.avRoute.snapshot.params[idParam];
    }

    this.form = this.formBuilder.group(
      {
        picker: [''],
        cost: ['', [Validators.required]],
        vehicleList: [''],
        startKm: ['', [Validators.required]],
        endKm: ['', [Validators.required]],
        liter: ['', [Validators.required]],
        average: ['', [Validators.required]]
      }
    )

    of(this.vehicleService.getVehicles().subscribe(data=> (
      this.vehicles = data
    )))

  }

  ngOnInit() {
    if (this.fuelId > 0) {
      console.log(this.form);
      this.actionType = "Edit";
      this.fuelService.getFuel(this.fuelId)
        .subscribe(data => (
          this.existingFuel = data,
          this.form.get["picker"].setValue(data.date),
          this.form.get["cost"].setValue(data.cost),
          this.form.get["vehicleList"].setValue(data.vehicle.id),
          this.form.get["startKm"].setValue(data.startKm),
          this.form.get["endKm"].setValue(data.endKm),
          this.form.get["liter"].setValue(data.liter),
          this.form.get["average"].setValue(data.average)
        ));
    }
  }

  get picker() { return this.form.get("picker"); }
  get cost() { return this.form.get("cost"); }
  get vehicleList() { return this.form.get("vehicleList"); }
  get startKm() { return this.form.get("startKm"); }
  get endKm() { return this.form.get("endKm"); }
  get liter() { return this.form.get("liter"); }
  get average() { return this.form.get("average"); }
}

Answer №1

Not this:

this.form.get["inputName"].setValue(value);

This is the correct way:

this.form.get('inputName').setValue(value);

The get() function allows you to access controls within a form group. It is not used like an object property accessed with square brackets.

Answer №2

To modify a particular value, you can utilize patchValue as demonstrated below. Alternatively, if you intend to update all values within the form, you may opt for setValue.

this.form.patchValue({
    fieldName: updatedValue
});

Answer №3

This specific code snippet is designed to retrieve a certain field within the form. To access the corresponding value, use the following method:

this.form.value.inputName;

If you intend to update a single element in the form, utilize the patchValue function instead:

this.form.patchValue({ inputName: value });

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 are the best practices for integrating Qt with React in TSX?

While I've figured out how to communicate qt with JS successfully, the challenge arises when trying to use React in TSX for frontend development. The previous solution failed on this front. Backend code: #./main.py import os from PySide6.QtWidgets ...

Leveraging both the spread operator and optional fields can improve the productivity and readability of your

Imagine you have an object with a mandatory field that cannot be null: interface MyTypeMandatory { value: number; } Now, you want to update this object using fields from another object, but this time with an optional field: interface MyTypeOptional ...

combination of Electron, Node.js, and Angular

Can I integrate Angular 5 into an Electron project and have Node.js run on the server side as well? While I understand Electron allows for desktop applications, I am curious if it can also support server-side applications. Additionally, I am unsure if it ...

Exploring the Flow of Angular 5 HttpInterceptor

Implementing HttpInterceptor in one of my Angular applications to display a spinner for every request has been successful. However, I have encountered an issue with displaying an Error modal using a notificationService that utilizes SweetAlert. The code sn ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Having trouble integrating ColorThief with Angular, encountering issues with missing library methods?

I am attempting to integrate the Library ColorThief () into an Angular 12 project, but unfortunately, I have been unable to make it work. I started by running $ npm i --save colorthief and then in my desired component .ts file: const ColorThief = require ...

Including a Script Tag in an Angular 2 Application with a Source Attribute retrieved from a Web API Request

Situation: Within my Angular 2+ application, I am utilizing a web API to retrieve URLs for script tags created by a function called loadScript during the AfterViewInit lifecycle hook. The web API is providing the expected JsonResult data, which I have suc ...

Having trouble with importing and receiving the error message "Module 'clone' not found."

When trying to use clone.js in Angular 2, I imported it with import * as clone from 'clone'. It was listed in my package.json dependencies and successfully imported into node_modules. However, when viewing the output, I encountered the error mes ...

When working with Material-UI and TypeScript, the type '{ children: never[]; }' does not share any properties with the type 'IntrinsicAttributes'. This can lead to incompatible types error messages in your code

As a beginner in TypeScript, I am attempting to incorporate an existing component, specifically tabs from material-ui. Here is the code in SimpleTab.ts: import React from 'react'; import { makeStyles, Theme } from '@material-ui/core/styles ...

Tab order in Angular Forms can be adjusted

While constructing a two-column form for simplicity, I utilized two separate divs with flexbox. However, the tabbing behavior is not ideal as it moves down the form rather than moving across when using the tab key to navigate between inputs. I am seeking a ...

Angular form requests can utilize the Spring Security Jwt Token to allow all options methods

Despite checking numerous sources online, I am facing a persistent issue with my Angular application. The problem arises when using HttpClient along with an Angular interceptor to set headers for authentication in my Java Rest API using JWT tokens. The int ...

Incorporate Angular application with SAML protocol

Greetings! I am a beginner in both Angular and SAML. I have recently embarked on creating an Angular 6 application and now I am looking to integrate this application with SAML for implementing a login module using VIDM. However, I am unsure of how to go ...

How to implement angular 2 ngIf with observables?

My service is simple - it fetches either a 200 or 401 status code from the api/authenticate URL. auth.service.ts @Injectable() export class AuthService { constructor(private http: Http) { } authenticateUser(): Observable<any> { ...

Execute a sequence of HTTP requests within an Angular interceptor or service when certain values are found to be null

My goal is to send a series of http requests in order to retrieve essential data that needs to be added to my request parameters for backend logging reasons. For instance, I require the userName, which can be obtained from the Microsoft endpoint: by fetc ...

Incorporate a new method into a TypeScript class from a separate file

I'm curious about the feasibility of adding additional functions to a class prototype in Typescript. Here's my dilemma: I have a file containing a class, for example image.ts: export class Image { b64img: string; } Since this class is gene ...

Token does not contain the necessary claim nbf (not before) for access while utilizing Firebase Microsoft Sign-in to retrieve data from MicrosoftGraph

I currently have a mobile application structured with Angular on the front-end and a Node.js server on the backend. We have successfully integrated Google Cloud's Identity Providers for users to sign in using Google and/or Microsoft accounts. While ...

Resetting the state back to its initial value - which one to use: useState or useReduce?

In order to enhance the functionality of a third-party Authentication service Auth0's useAuth0 hook, I have developed a custom hook called useAuth. This custom hook is responsible for managing local variables that store essential user information like ...

Issue with auto-completion not working for Typescript module imports in a nested project architecture or npm workspaces

My project has a complex setup with multiple distributed npm packages that have dependencies on each other. I've tried to simplify the structure as much as possible. The setup is structured like this (each subproject having its own package.json): Proj ...

The conversion of an array to Ljava/lang/Object is not possible

I'm currently working on a project using NativeScript app with TypeScript where I am trying to pass an array of android.net.Uri to a function. However, when attempting to do so, I encounter an error mentioning that the 'create' property does ...

Create a custom button in Material-UI using Styled-components, and integrate it with React

I'm currently working on a project using React, TypeScript, and styled components along with the material-ui library. I have created styled material-ui buttons as shown below: import React from 'react' import styled from 'styled-compone ...