Troubleshooting form submission issues in Angular 4

I am encountering a few issues with my search form. It is supposed to function as a search tool with one input field and one button. However, something seems amiss. I am utilizing an API that returns values based on the string inputted. When an empty value is sent, it should return all possible values.

The main problem arises when I submit the form. I am faced with errors such as:

  1. Cannot read property 'value' of undefined;
  2. _this.form.get is not a function.

Below is the code snippet:

Service

@Injectable()
export class FleetService {
  private defUrl = 'some.url';

  constructor(private http: Http) { }

  getFleet(fleetname?: string) {
    const url = (!fleetname) ? this.defUrl : 'some.url=' + fleetname;
    return this.http.get(url)
      .map(res => res.json());
  }
}

Component

export class FleetComponent implements OnInit {

  ngOnInit() {
    this.searchQuery = new FormGroup({
      fleetname: new FormControl('', Validators.required)
    });
  }

  public flota: FleetHead[];
  public searchQuery: FormGroup;

  constructor(private fleetService: FleetService, private router: Router) {
    this.fleetService.getFleet().subscribe(fleet => {
      this.flota = fleet;
    })
  }

  search(searchQuery) {
    this.fleetService
      .getFleet(searchQuery.value.fleetname)
      .subscribe(searchQuery => {
        this.searchQuery = searchQuery;
        this.router.navigate(['/fleet']);
      })
  }

}

interface FleetHead {
  fleets: FleetInfo[];
}

interface FleetInfo {
  id: number;
  name: string;
}

Template

<form class="form-inline" novalidate (ngSubmit)="search(fleetname)" [formGroup]="searchQuery">
  <div class="form-group">
    <input class="form-control" formControlName="fleetname" type="text" placeholder="Search">
  </div>
  <button class="btn btn-info" type="submit">Search</button>
</form>

<div *ngIf="flota">
  <p-dataTable [value]="flota.fleets">
    <p-header>Search results</p-header>
    <p-column field="id" header="ID" [sortable]="true"></p-column>
    <p-column field="name" header="Name" [sortable]="true"></p-column>
  </p-dataTable>
</div>

While using this template, I encountered the error

Cannot read property 'value' of undefined
. When I added #fleetname to the input, it resulted in _this.form.get is not a function.

This template operates on route /fleet, and upon submission, I aim to remain on the page with updated values for potentially different search results.

Answer №1

The error message you are receiving indicates that you are trying to access a property ('value') of an undefined object.

The specific error is 'cannot read property 'value' of undefined'

This issue occurs because the value being passed in your submit function is incorrect. It should be:

(ngSubmit)="search(searchQuery)"

With this setup, make sure your function is structured like this to correctly handle the search query:

this.fleetService
  .getFleet(searchQuery.value.fleetname)
     .subscribe(...)

In addition, there is no need to use router navigate in this scenario so you can remove the following line:

this.router.navigate(['/fleet']);

To ensure that the values get updated after performing the search, consider updating the variable flota with the results instead of searchQuery. Your function should look something like this:

search(searchQuery) {
  this.fleetService
    .getFleet(searchQuery.value.fleetname)
    .subscribe(searchQuery => {
      this.flota = searchQuery;
    })
}

You can find a demo of this setup using omdbapi by clicking on this link:

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

The submit button is getting disrupted by the background image being set

Implement the following CSS code to set a background image on a single-page app (Angular). .page::before { content: ''; position: absolute; background-size: cover; width: 100%; height: 100%; background-image: url("../../assets/weird. ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Creating Dynamic ion-card Elements in Typescript by Programmatically Changing Values

Currently, I am working on a basic app that retrieves posts from the server and displays them as cards on the screen. At this early stage, one of my main challenges is figuring out how to dynamically add ion-card elements with changing content and headers ...

Creating a library in Angular2 with multiple routes: a step-by-step guide!

Having recently delved into Angular2, I find myself in need of building a reusable library to be utilized by multiple applications as an html tag. This library will consist of various pages such as search, create, edit, etc., each requiring different rout ...

`The validation in Angular 12 is successful, yet the mat-input remains invalid.`

Code snippet of Component- ngOnInit(): void { this.form = this.fb.group({ currentPassword: ['', [Validators.required], [this.matchCurrentPassword]], newPassword: ['', [Validators.required, Validators.minL ...

Breaking down types in Typescript: Extracting individual types from an object containing multiple objects

Having a query: const queries = { light: { a... b... }, dark: { a... b... c... d... }, The react element requires a colors parameter that corresponds to one of the themes in the above object, with each theme containing a un ...

Exploring the correct navigation of page objects through Protractor using TypeScript

I'm working on setting up a protractor test suite with TypeScript and running into an issue involving chaining of pageObjects for multiple pages. I haven't seen any examples that deal with this specific scenario. I've simplified the example ...

What are the essential requirements for an Angular application to function properly with minimal dependencies?

If a new developer wants to begin learning Angular from scratch, what are the essential npm packages that they need to install in order to start building an Angular application with minimal dependencies? ...

What is the best way to select and style individual HTML elements using CSS?

Having trouble editing a Validations Form in Ionic 4 with CSS. It seems that only the form elements are targeted after clicking on the form group. Attached below are the form states before and after click. I'm unable to style the form elements before ...

What is the best way to eliminate the final character in an input value once it has passed through regex validation in Angular8

Hello! I am attempting to remove the last digit of a string and update the input value each time my function checks if the input value passes a regex test on keypress. Initially, it works correctly, but then it adds an extra digit. After that, it works a ...

What could be the reason for `process.env.myvariable` not functioning in a Next.js project with TypeScript

After creating a file called .env.local in the root directory of my project, I added a variable called WEBSOCKET_VARIABLE=THIS_IS_TEXT to it. However, when I try to access it using process.env.WEBSOCKET_VARIABLE, nothing is found. What could be causing ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

The imported js elements from Bootstrap are failing to function properly despite being successfully included

I want to utilize the collapse feature from Bootstrap in my project. To do so, I have installed jQuery and popper.js: "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/hover.css/css/hover.css", "node_modules/hambur ...

An error is being thrown in the Angular build due to an issue with parsing JSON after stripping out

Currently, I am working with angular nx alongside nestjs. Upon cloning the project and executing the yarn command, it successfully builds. However, whenever I try to install any package and compile the project, an error is thrown: **D:\projectNAme&bso ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Issue with Angular 2: Route guard failing to work after browser refresh

Defining these routes in app.module.ts: ... { path: 'mypath', component: MyComponent, canActivate: [RouteGuard] }, { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '**', redirectTo: '/ho ...

Creating a function that is accessible to the entire module

Creating a universal function in a file that is not a module: example.ts: function example() {} You can easily call this function from another file, say test.ts, without needing to import the function from example.ts: test.ts: example(); // calling univ ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

404 Error message encountered across all routes in a Node TypeScript Azure Function App - Resource not located

I keep encountering a 404 Not Found error on all routes while requesting my API. I am struggling to correctly write the code. Here's an example of my code: host.json: { "version": "2.0", "extensions": { & ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...