如何用Angular Forms替代ngModel实现搜索筛选功能?
改用Angular Forms实现搜索筛选(含双向数据绑定)
先模拟你原有的ngModel实现代码作为对比,再给出两种Angular Forms的改造方案:
原有ngModel实现参考
HTML模板
<input type="text" [(ngModel)]="searchTerm" (input)="filterItems()" placeholder="搜索..." /> <ul> <li *ngFor="let item of filteredItems">{{ item.name }}</li> </ul>
TypeScript代码
import { Component } from '@angular/core'; @Component({ selector: 'app-search-filter', templateUrl: './search-filter.component.html', styleUrls: ['./search-filter.component.css'] }) export class SearchFilterComponent { searchTerm = ''; items = [ { name: 'Angular' }, { name: 'React' }, { name: 'Vue' }, { name: 'Svelte' } ]; filteredItems = [...this.items]; filterItems() { this.filteredItems = this.items.filter(item => item.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ); } }
方案一:模板驱动表单实现
1. 依赖配置
确保在AppModule中导入FormsModule:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { SearchFilterComponent } from './search-filter/search-filter.component'; @NgModule({ declarations: [AppComponent, SearchFilterComponent], imports: [BrowserModule, FormsModule], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2. 组件代码改造
HTML模板(双向绑定写法)
模板驱动表单中仍可使用[(ngModel)],但必须给控件指定name属性或设置独立模式:
<form #searchForm="ngForm"> <input type="text" name="searchTerm" [(ngModel)]="searchTerm" (input)="filterItems()" placeholder="搜索..." /> </form> <ul> <li *ngFor="let item of filteredItems">{{ item.name }}</li> </ul>
注:若不想包裹在
<form>标签中,可添加[ngModelOptions]="{standalone: true}"替代name属性。
TypeScript代码
与原ngModel版本几乎一致,无需额外修改:
import { Component } from '@angular/core'; @Component({ selector: 'app-search-filter', templateUrl: './search-filter.component.html', styleUrls: ['./search-filter.component.css'] }) export class SearchFilterComponent { searchTerm = ''; items = [ { name: 'Angular' }, { name: 'React' }, { name: 'Vue' }, { name: 'Svelte' } ]; filteredItems = [...this.items]; filterItems() { this.filteredItems = this.items.filter(item => item.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ); } }
方案二:响应式表单实现
1. 依赖配置
在AppModule中导入ReactiveFormsModule:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { SearchFilterComponent } from './search-filter/search-filter.component'; @NgModule({ declarations: [AppComponent, SearchFilterComponent], imports: [BrowserModule, ReactiveFormsModule], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2. 组件代码改造
TypeScript代码
创建FormControl实例,监听值变化触发筛选(可添加防抖优化):
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { debounceTime } from 'rxjs/operators'; @Component({ selector: 'app-search-filter', templateUrl: './search-filter.component.html', styleUrls: ['./search-filter.component.css'] }) export class SearchFilterComponent implements OnInit { searchControl = new FormControl(''); items = [ { name: 'Angular' }, { name: 'React' }, { name: 'Vue' }, { name: 'Svelte' } ]; filteredItems = [...this.items]; ngOnInit() { // 防抖300ms避免频繁触发筛选 this.searchControl.valueChanges.pipe(debounceTime(300)) .subscribe(searchTerm => { this.filterItems(searchTerm || ''); }); } filterItems(searchTerm: string) { this.filteredItems = this.items.filter(item => item.name.toLowerCase().includes(searchTerm.toLowerCase()) ); } }
HTML模板(双向绑定写法)
响应式表单有两种双向绑定方式:
<!-- 方式1:直接绑定FormControl(推荐) --> <input type="text" [formControl]="searchControl" placeholder="搜索..." /> <!-- 方式2:结合[(ngModel)]使用(需同时导入FormsModule+ReactiveFormsModule) --> <input type="text" [(ngModel)]="searchControl.value" [ngModelOptions]="{standalone: true}" placeholder="搜索..." /> <ul> <li *ngFor="let item of filteredItems">{{ item.name }}</li> </ul>
Angular Forms双向绑定总结
1. 模板驱动表单
- 核心写法:
[(ngModel)]="property" - 强制要求:控件需指定
name属性,或设置[ngModelOptions]="{standalone: true}" - 适用场景:简单表单、快速开发场景
2. 响应式表单
- 单控件场景:
[(ngModel)]="control.value" [ngModelOptions]="{standalone: true}" - 多控件场景(结合
FormGroup):// TS代码 searchForm = new FormGroup({ searchTerm: new FormControl('') });<!-- HTML代码 --> <form [formGroup]="searchForm"> <input type="text" [(formControlName)]="searchTerm" placeholder="搜索..." /> </form> - 适用场景:复杂表单、需要表单验证/状态监听、动态表单场景
内容的提问来源于stack exchange,提问作者Mark Baumann
相关产品推荐
相关产品推荐

