簡體   English   中英

將輸入從component.html發送到component.ts

[英]Send input from component.html to component.ts

我正在搜索,並且正在我的component.html上從用戶那里接收需要搜索的值。

我正在將數據發送到component.ts就像下面的代碼一樣。

<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)">Buscar</a>

在我的component.ts我有以下代碼

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

我的疑問是,為什么window.location.href 總是Firefox Developer Edition上的瀏覽器中總是更改 current URL ,而有時僅在Google ChromeFirefox Quantum上才更改

如果單擊按鈕 ,它將始終按預期運行,但是如果按回車 ,則在其他兩個瀏覽器上才能運行 ,並且我不知道為什么會發生這種情況,你們可以幫我嗎?

  • 編輯

我在調試時注意到,當我按Enter鍵時,它不會調用函數search

實際上,您在使用(keyup.enter)時就在使用(key.enter) 另外,您不需要引用#query 您可以將輸入編寫為:

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

在方法中使用:

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

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

看來FireFox正在抓緊keyup而不enter

我找到了一個解決方案,已將<input>標記內容和標記<a>更改為<button> ,如下面的代碼

<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>

在我的組件中,我有下面的代碼

export class MyComponent implements OnInit {
    query = ''; // Global variable in my component

    constructor() {}

    ngOnInit() {
    }

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

在我的app.module.ts添加了以下幾行

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM