Home > OS >  Using Angular Forms instead of ngModel
Using Angular Forms instead of ngModel

Time:11-15

I have following Code with ngModel, which is working. HTML:

<div >
  <div >
      <input  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?

CodePudding user response:

You can just use the following code:

HTML:

<div >
  <div >
      <input  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.

CodePudding user response:

Remove the pipe, use valuechanges and filter with rxjs.

Template

<div >
  <div >
    <input
      
      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

  • Related