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

Creating a new project in ASP Net Core Angular using Bootstrap 4 for the SideMenu layout instead of Bootstrap 3

I am currently working on developing a website using Angular6, where I aim to have a vertical navbar for large screens and a top navbar with dropdown functionality for mobile devices. While searching online, I came across several examples that seemed overl ...

Retrieve the value within the finalize pipe from a test execution

I have a component with the following code: isLoading: boolean; users: User[]; test: number = 1; ngOnInit() { this.isLoading = true; this.userService.getUsers() .pipe( finalize(() => { // Disable loading when complete ...

Manipulate inherited CSS styles from an external source

Currently, I am working on creating a pagination using the NG-Bootstrap pagination component. However, I encountered an issue where I need to modify or specifically remove some CSS properties that are applied by default in the NG-Bootstrap library. Is ther ...

Display a nested component post initialization in Angular

<ng-container *ngIf="isTrue; else notTrue"> <app-child [property1]="value" [property2]="value" [property3]="value" (function1)="func($event)" ></app-child> </ng-container> <ng-t ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

Cannot execute npm packages installed globally on Windows 10 machine

After installing typescript and nodemon on my Windows 10 machine using the typical npm install -g [package-name] command, I encountered a problem. When attempting to run them through the terminal, an application selector window would open prompting me to c ...

Setting default values using forRoot is functioning correctly in development mode, but encountering issues in production mode (AoT)

The code runs smoothly in development mode, but encounters issues in production: Module export class SpinnerModule { static forRoot(config?: SpinnerConfig): ModuleWithProviders { return { ngModule: SpinnerModule, providers: [SpinnerServ ...

Ways to turn off Typescript alerts for return statements

I'm looking to turn off this Typescript warning, as I'm developing scripts that might include return values outside of a function body: https://i.stack.imgur.com/beEyl.png For a better example, check out my github gist The compiled script will ...

Navigate to a blank page using Angular once the button has been clicked

Having a simple home page with just one button, I wanted the user to be redirected to another page upon clicking the button. However, my attempts to achieve this have not been successful. Here's the code snippet from my app.component.ts file: app.com ...

Displaying the component that was provided as a parameter

I am looking to develop a custom component that can take another component as a parameter and then embed it within an NgBootstrap modal while also incorporating additional HTML elements. I am unsure if this is achievable, but my goal is to enhance modals ...

Updating a value from a provider in Angular: A step-by-step guide

I have an AppModule provider that provides a specific class. Is it possible to change the provided value dynamically at runtime? {provide: MatDatepickerIntl, useClass: SomeClass} How can I switch from using SomeClass to AnotherClass on the fly (for examp ...

Combine arrays using union or intersection to generate a new array

Seeking a solution in Angular 7 for a problem involving the creation of a function that operates on two arrays of objects. The goal is to generate a third array based on the first and second arrays. The structure of the third array closely resembles the f ...

Obtain the combination of values within an array object

I am attempting to write the specifications for a function that can take records of any structure and convert the values into a discriminated union. For example: const getKeys = <T extends {key: string}>(items: T[]): T['key'] => { // ...

Selecting multiple items using PrimeNG's AutoComplete with preselected values

Is there a method for displaying preselected values in PrimeNg AutoComplete Multiple mode? I attempted to include <p-autoComplete value="myValue"></p-autoComplete>, but it had no effect. ...

Using Typescript: Generate keys in function return depending on parameter

Currently in the process of developing an SDK for a Rest API that includes an embed request parameter to fetch additional resources and add them to the response. I am exploring if there is a way, using Typescript, to extract these embed parameters while de ...

Connect an Observable to the template with async binding

I've been attempting to link an Observable to a template variable in Angular using the following code: [class.active]="isBookmarked$ | async" During the ngOnInit function, I initialize the Observable: var promise = this.cacheService.getItem(this.bo ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

Unique loading animations are assigned to each individual page within the Next.js framework

Is there a way to have unique loading animations for each of my website pages during the loading process? How can I achieve this? I've attempted to put the loading component on the page component directly, but it doesn't seem to work: //Page com ...

What is the equivalent of Buffer.from(<string>, 'hex') in Python?

I am currently facing the challenge of translating a Typescript library into Python. The specific library I am working with is bs58 in Typescript and its counterpart base58 in Python. My issue arises when attempting to replicate the following code: const ...