使用Angular Forms而不是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>

打印稿:

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'}
];
}

我怎么写这个代码与角形式?我读到还有一种双向数据绑定。

请人帮忙好吗?

您可以使用以下代码:

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

删除管道,在rxjs中使用valuechanges和filter

模板

<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

最新更新