- 在 app.module.ts 文件中导入 FormsModule 和 ReactiveFormsModule
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- 在组件HTML模板中添加搜索输入框和按钮
- 在组件代码中添加以下代码来初始化搜索表单控件并定义 search() 方法:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
searchTerm: string;
searchField: FormControl;
constructor() {
this.searchField = new FormControl();
}
search() {
console.log('Search term:', this.searchTerm);
// 执行搜索逻辑
// ...
}
}
- 在 search() 方法中添加搜索逻辑,如发送网络请求并显示结果
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
searchTerm: string;
searchField: FormControl;
searchResults: any[];
constructor(private http: HttpClient) {
this.searchField = new FormControl();
}
search() {
console.log('Search term:', this.searchTerm);
this.http.get(`http://example.com/search?q=${this.searchTerm}`).subscribe((data: any[]) => {
this.searchResults = data;
console.log('Search results:', this.searchResults);
});
}
}