Pass data from the HTML component to the TypeScript component

When conducting a search, I prompt the user to enter the value they are looking for in my component.html.

The data is then sent to the component.ts using the following code:

<input class="form-control mr-sm-2" #query (keyup.enter)="search(query.value)">
<a class="btn btn-light my-2 my-sm-0" (click)="search(query.value)">Search</a>

In my component.ts, the function looks like this:

search(query: string) {
    if (query !== '') {
        window.location.href = 'http://mydomain/result.html?name=' + query;
    }
}

I'm puzzled as to why window.location.href always changes the current URL in the browser when using Firefox Developer Edition, but only sometimes does so in Google Chrome and Firefox Quantum.

Clicking on the button consistently works as expected, but hitting "enter" only triggers the function occasionally in the other two browsers. I'm unsure why this discrepancy occurs and would appreciate any insights or solutions you may have to offer.

  • EDIT

Upon debugging, it appears that pressing "enter" doesn't always execute the search function.

Answer №1

Instead of (keyup.enter), you should be using (key.enter). Also, there is no need for the reference #query. Update your input tag to:

<input class="form-control mr-sm-2" (key.enter)="search($event)">

Modify your method as follows:

search(event: Event) {
    const query = (event.target as HTMLInputElement).value;

    if (query !== '') {
        window.location.href = 'http://mydomain/result.html?name=' + query;
    }
}

FireFox may interpret keyup differently than enter.

Answer №2

I stumbled upon a solution by making changes to the <input> tag content and replacing the <a> tag with <button>, see the updated code below:

<input type="text" class="form-control mr-sm-2" [(ngModel)]="query" name="busca">
<button type="submit" class="btn btn-light my-2 my-sm-0" (click)="search()">Buscar</button>

In my component, I have implemented the following:

export class MyComponent implements OnInit {
    query = ''; // This is a global variable in my component

    constructor() {}

    ngOnInit() {
    }

    search() {
        if (this.query !== '') {
            window.location.href = 'http://mydomain/result.html?name=' + this.query;
        }
    }
}

I made corresponding changes in my app.module.ts file as well:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // Imported FormsModule here

import { AppComponent } from './app.component';
import { MyComponent } from './my/my.component';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    MyComponent
  ],
  imports: [
    BrowserModule,
    FormsModule  // Added FormsModule here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

Encountering a 404 error with systemjs-angular-loader.js in a production environment

Currently, I am working on the most recent Angular/Quickstart project that utilizes systemjs-angular-loader.js to load app-relative HTML templates without the need for the moduleId property. During development and testing with "npm start" to serve pages, ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Executing a JavaScript utility before running a collection in Postman: Step-by-step guide

Regarding my needs Before executing the Postman Collection, I need to complete a few preliminary steps: I need to use a JavaScript utility to generate JSON file containing input BODY data The generated JSON file will then be used by another utility to cre ...

Using jQuery to set cookies for multiple domains

I am trying to set a cookie for a domain that should also be accessible for a subdomain. For example, www.mydomain.com and sub.mydomain.com However, when I set the cookie for the main domain, it does not seem to work for the subdomain. I am using the jQu ...

Are DOM Events compatible with ajax-loaded content that cannot be unloaded?

How should events be managed with ajax-loaded content that can be hidden or displayed? I have created a sidebar in HTML that toggles visibility on click, along with two pages that are loaded using ajax. When the sidebar is hidden or displayed, I need to ...

running a loop with a data-attribute conditional statement causes the browser to crash

Currently, I am working on a code snippet that involves hiding elements if the data attribute of a clicked link does not match the data attribute of a specific section. My approach is to iterate through the title elements that do not match the data attribu ...

Is it possible to extract the value from the JSON response using this.responseText?

Having trouble extracting data from a json response This is the HTML code I am using. index.html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head ...

Turning off and on CSS transitions to set the initial position

Is there a way in javascript to position divs with rotations without using transitions initially for an animation that will be triggered later by css transition? I have tried a codepen example which unfortunately does not work on the platform but works fin ...

PhantomJS encountered an issue: Attempting to access the 'write' member of a deleted QObject is not allowed

I am in the process of creating a web API on port 7788 that will accept JSON data. This JSON data will then be passed to my API which will render a website. Next, PhantomJS will search for an element on that page and the web API on port 7788 should return ...

Tips on fixing the Angular error: "Argument of type '" | "" | Date' is not compatible with the parameter type 'string | number | boolean."

Currently in Angular-14, I am working on implementing a server-side search filter and pagination. Below is the code snippet that I am using: When fetching data from the web api endpoint, the startDate and endDate values are received as Date format (e.g., ...

Updating state in React is not possible

I am having trouble updating my state (specifically with setCoords). The API request is returning a 200 status code and the elements I need are present: https://i.stack.imgur.com/a8QzN.png Below is the code I am working with: const App = () => { co ...

Merge the properties of two class instances deeply

What is the best method for deep merging two instances of ES6 classes similar to lodash? The end result should be an instance of the same class with a deep merge of both instances' properties. ...

How to use Javascript to set focus on a dropdown list within a PHP script

Having trouble setting focus on the dropdown list in my PHP page dc-test.php, where there are two dropdown lists that are interdependent. The values for these dropdown lists are fetched from a database table. I am unable to set focus on the first dropdown ...

NuxtJs login feature is functional, but encounters an unauthorized 401 error

I am utilizing the NuxtJs auth module to manage my authorization within the application state. I have created an express API specifically for this purpose, and it functions correctly. Below is the configuration included in my nuxt.config.js file: axios ...

Having difficulty populating a selection box through an ajax request in Django

I am facing an issue with creating cascading select boxes in my project (backend Django), although I believe most of the backend work has been completed. The JavaScript code I'm using is adapted from a solution found on a stackoverflow post. $(docume ...

Navigating a Facebook page login can have its challenges. Let's uncover the

Facebook now allows pages to be created without any associated Facebook users. These unowned pages are also able to sign into applications. How can an application identify and manage this scenario? Logout of Facebook Create a new Facebook page You have s ...

Embedding HTML code in JavaScript

I am in the process of developing a karaoke-style website where I aim to incorporate HTML elements along with text. My intention is to introduce a break tag that will display certain lyrics on a separate page. You can access the codepen for this project h ...

What is the best way to capture and store the chosen text in a Kendo multiselect variable?

I recently transformed the kendo dropdownlist into a kendo multiselect. The dropdownlist now has 2 items: D-UDMS-TMA Data Mgmt System U-TDMS-SMA Mgmt System $("#btnSendFlow").click(function () { debugger; var FlowData_array = ...

I encountered a ReferenceError while working on my Google Authentication code, specifically stating that the variable "id" is not defined

I've encountered an issue with authentication in my code and I'm having trouble retrieving the ID that is already created. Here's the code snippet: require('dotenv').config() const express = require("express"); const bod ...

Using jQuery effects on your PHP message to give it an interactive touch - here's how!

For some time now, my website has had a straightforward PHP message system that worked well, storing data into MySQL with each message having a unique ID. Recently, out of the blue, I decided to enhance the system by adding jQuery effects for sending and d ...