Search code examples
angularangular-formsngmodel

Using Angular Forms instead of ngModel


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?


Solution

  • 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.