-1

I have following Code with ngModel, which is working. 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'}
];
}

How can I write this code with angular forms? I read there is also a two way data binding.

Can please someone help?

Mark Baumann
  • 98
  • 10

2 Answers2

2

You can just use the following code:

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

Please remember to import ReactiveFormsModule in your module.

Fabian Strathaus
  • 3,192
  • 1
  • 4
  • 26
1

Remove the pipe, use valuechanges and filter with rxjs.

Template

<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),
  );

Play with this on stackblitz: https://stackblitz.com/edit/angular-wigwzh?file=src/app/app.component.ts

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43