【问题标题】:How would I get an input value from a textbox?如何从文本框中获取输入值?
【发布时间】:2018-04-17 21:29:59
【问题描述】:

我正在开发搜索功能。但是,我似乎无法从文本框中获取值。

搜索栏组件

import { Component, OnInit, Input } from '@angular/core';

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

  searchQuery: HTMLElement;
  searchQuerystr: string;

  constructor() { }

  ngOnInit() { }

  getinput(): void {

    this.searchQuerystr = document.getElementById('input').innerHTML;
    console.log(this.searchQuerystr);
  }
}

搜索栏 HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- The form -->
<div>
<form class="searchbar">
  <input type="text" id="input" placeholder="Search movies..">
  <button type="submit" (click)="getinput()"><i class="fa fa-search"></i></button>
</form>
<app-searchresult [searchQuerystr]='searchQuerystr'></app-searchresult>
</div>

我正在尝试将搜索查询发送到子组件

搜索结果组件

@Component({
  selector: 'app-searchresult',
  templateUrl: './searchresult.component.html',
  styleUrls: ['./searchresult.component.css']
})
export class SearchresultComponent implements OnChanges {
  @Input() searchQuerystr: string;

  searchResult: IRootResult[] = [];
  movie: IMovie;
  selectedMovie: IMovie;
  query: string;

  constructor(private _searchresultservice: SearchresultService) { }

  ngOnChanges() {
    // this.searchQuerystr = this.query;
    if (this.searchQuerystr) {
      this._searchresultservice.SearchDatabase(this.searchQuerystr)
        .subscribe(searchResult => {
          this.searchResult = searchResult;
        },
          error => console.log(error)
        );
    }
  }

  onSelect(movie: IMovie): void {
    this.selectedMovie = movie;
    window.setTimeout(function () { window.scrollTo(0, 1665); }, 300);
  }
}

由于来自文本框的输入未定义,我收到未定义的错误。 有关如何解决此问题的任何建议?

【问题讨论】:

  • 您可以使用 2 路绑定,然后将检索到的数据传播到服务中。然后可以在您的其他组件中引用此服务。

标签: angular typescript


【解决方案1】:

SearchBar HTML 中使用ngModel

...
<input [(ngModel)]="searchQuerystr" type="text" id="input" placeholder="Search movies..">
...

【讨论】:

  • 感谢Aboudeh87 的建议!使用ngModel后,如何将数据发送到子组件?
  • 每次您在输入中写入任何内容时都会发送,因为它是 2 路绑定
  • 每次searchQuerystr的值发生变化,这个值会通过这个代码&lt;app-searchresult [searchQuerystr]='searchQuerystr'&gt;传递给子组件
猜你喜欢
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 2013-06-07
相关资源
最近更新 更多