首页 > 解决方案 > 如何做一个 AngularTS 工作搜索框?

问题描述

我需要制作一个有效的搜索框。此代码不起作用。你能帮我修一下吗?

html:

<form #f="ngForm" (ngSubmit)="onSubmit(f)" #searchForm="ngForm">
  <input type="search" placeholder="Search...">
</form>

搜索表单组件:

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

  users: User[];
  private s: String;

  constructor(private route: ActivatedRoute, 
    private router: Router, 
      private userService: UserService)  { }

      onSubmit(f: NgForm) {
      this.userService.findByFS(f.value).subscribe(data => {
              this.users = data;})
    }
}

标签: htmlangular

解决方案


我修改了你的代码。它应该像那样工作。您可以在https://angular.io/api/forms/NgForm查看使用情况。

模板:

<form #f="ngForm" (ngSubmit)="onSubmit(f)">
  <input name="search" type="search" ngModel placeholder="Search...">
</form>

零件:

@Component({
  selector: 'app-search-form',
  templateUrl: './search-form.component.html',
  styleUrls: ['./search-form.component.css']
})
export class SearchFormComponent {
  users: User[];

  constructor(private userService: UserService)  {}

  onSubmit(f: NgForm) {
    this.userService.findByFS(f.value.search).subscribe(data => this.users = data);
  }
}

推荐阅读