[英]Using Angular Forms instead of ngModel
我有以下代碼和 ngModel,它正在工作。 HTML:
<div class="container">
<div class="search-name">
<input class="form-control" type="text" name="search" [(ngModel)]="searchText" autocomplete="on" placeholder=" SEARCH ">
</div>
<ul *ngFor="let name of names | filter:searchText">
<li>
<span>{{name.country}}</span>
</li>
</ul>
</div>
TypeScript:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'search-filter-angular';
searchText: any;
names = [
{ country: 'Adil'},
{ country: 'John'},
{ country: 'Jinku'},
{ country: 'Steve'},
{ country: 'Sam'},
{ country: 'Zeed'},
{ country: 'Abraham'},
{ country: 'Heldon'}
];
}
我如何用 angular forms 編寫這段代碼? 我讀到還有一種雙向數據綁定。
可以請人幫忙嗎?
您可以只使用以下代碼:
HTML:
<div class="container">
<div class="search-name">
<input class="form-control" type="text" name="search" [formControl]="searchText" autocomplete="on" placeholder=" SEARCH ">
</div>
<ul *ngFor="let name of names | filter: (searchText.valueChanges | async)">
<li>
<span>{{name.country}}</span>
</li>
</ul>
</div>
TS:
title = 'search-filter-angular';
searchText = new FormControl();
names = [
{ country: 'Adil' },
{ country: 'John' },
{ country: 'Jinku' },
{ country: 'Steve' },
{ country: 'Sam' },
{ country: 'Zeed' },
{ country: 'Abraham' },
{ country: 'Heldon' },
];
請記住在您的模塊中導入ReactiveFormsModule
。
刪除 pipe,使用 valuechanges 並使用 rxjs 進行過濾。
模板
<div class="container">
<div class="search-name">
<input
class="form-control"
type="text"
name="search"
[formControl]="searchText"
autocomplete="on"
placeholder=" SEARCH "
/>
</div>
<ul *ngFor="let name of filteredNames$ | async">
<li>
<span>{{ name.country }}</span>
</li>
</ul>
</div>
TS
searchText = new FormControl();
names: MyName[] = [
{ country: 'Adil'},
{ country: 'John'},
{ country: 'Jinku'},
{ country: 'Steve'},
{ country: 'Sam'},
{ country: 'Zeed'},
{ country: 'Abraham'},
{ country: 'Heldon'}
];
filteredNames$: Observable<MyName[]> = this.searchText.valueChanges.pipe(
map(filter => filter ? this.names.filter(name => name.country.includes(filter)) : this.names),
startWith(this.names),
);
在 stackblitz 上玩這個: https://stackblitz.com/edit/angular-wigwzh?file=src/app/app.component.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.