角度8:如何将查询参数绑定到输入字段

时间:2020-02-02 22:29:57

标签: angular

我有一个带有输入字段的搜索页面,与Angular文档(https://angular.io/tutorial/toh-pt6#search-by-name)中的示例几乎相同。当用户在输入字段中键入搜索词时,就会发送一个ajax请求,搜索结果会显示在屏幕上。

我希望能够将输入字段中的搜索词2种绑定到URL查询参数,以便该URL始终代表当前搜索的详细信息,然后可以通过电子邮件等方式共享。

我找不到完成此操作的任何示例。 ActivateRoute.queryParamMap看起来是只读的。

到目前为止,我的代码与Angular实时示例中的hero-search组件几乎相同。 https://angular.io/generated/live-examples/toh-pt6/stackblitz.html

任何建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

  • 当用户在搜索框中键入内容时,您需要更改查询字符串:

    this.router.navigate([], {queryParams: {search: term}});
    
  • 当查询字符串更改时,搜索机制应从查询字符串中获取搜索词:

    this.heroes$ = this.route.queryParams.pipe(
          // take the search term from the query string
          map(query=>query.search),
          ...
    
  • 重新加载页面时,将搜索词带入模型:

    this.term = this.route.snapshot.queryParams.search;
    

    要实现此目的,请使用双向绑定:

    <input #searchBox [(ngModel)]="term" id="search-box" (input)="search(searchBox.value)" />
    

所以应该是这样的:

  constructor(
    private heroService: HeroService,
    private router: Router,
    private route: ActivatedRoute,
  ) {}

  // change the query string when the user type
  search(term: string): void {
    this.router.navigate([], {queryParams: {search: term}});
  }

  ngOnInit(): void {
    // take the current search term
    this.term = this.route.snapshot.queryParams.search;

    this.heroes$ = this.route.queryParams.pipe(
      // take the search term from the query string
      map(query=>query.search),

      // wait 300ms after each keystroke before considering the term
      debounceTime(300),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.heroService.searchHeroes(term)),
    );
  }

查看working demo

答案 1 :(得分:0)

使用Angular的two-way binding功能。

然后,而不是像这样仅进行单向绑定:

<input #searchBox id="search-box" (input)="search(searchBox.value)" />

您可以将ngModel元素的input属性双向绑定到组件内部的属性:

<input #searchBox id="search-box" (keyup)="search(searchQuery)" [(ngModel)]="searchQuery" />

每次用户输入新字符(让我们离开按键)时,都会调用(keyup)事件。