8

I have a list which I transform into a FormArray to generate a list of buttons in html. I want to filter the cars by name

CarComponent.html

  <input #searchBox id="search-box" (input)="search(searchBox.value)" />

<form [formGroup]="form" *ngIf="showCars">
              <input type="button" class ="btn"  formArrayName="carsList" *ngFor="let car of carsList$ | async; let i = index" value="{{carsList[i].name}}" >
        </form>

CarComponent.ts

 carsList$: Observable<Car[]>;
  private searchTerms = new Subject<string>();
  search(term: string): void {
    this.searchTerms.next(term);
  }

constructor(private formBuilder:FormBuilder,...)
{
  this.form = this.formBuilder.group({
      carsList: new FormArray([])
    });

this.addButtons();

}

 ngOnInit() {
    this.spinner.show(); 
    this.carsList$ = this.searchTerms.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((term:string)=> 
      this.carsList ??? // Is this correct ?? What do I put here ?
    )




  }

  private addButtons() {

      this.carsList.map((o,i)=>{
        const control = new FormControl;
        (this.form.controls.carsList as FormArray).push(control);
      })
    }

export const CarsList: Car[] = [
  { name: 'Mercedes' },
  { name: 'BMW' },
  { name: 'Porsche' },
  { name: 'Cadillac' }
]

So I would like to know how to do the filtering correctly, without using pipe for performance reasons.

TropicalViking
  • 407
  • 2
  • 9
  • 25
  • why do you use a FormArray? A FormArray is used if we has an array of "inputs", not a series of "buttons" – Eliseo Mar 10 '19 at 12:08
  • is `this.carsList ???` actually `this.carsList$` Just to understand right: You want to `const CarList` filtered according to the supplied searchTerm and then generate buttons for every car found? – Arikael Mar 10 '19 at 12:32
  • Arikael, yes. I want to filter CarsList which contains all the cars. CarList$ is an observable which will contain the filtered cars. – TropicalViking Mar 10 '19 at 12:44

1 Answers1

-1

You can use the Array filter fucntion along with Array includes to Filter out a value in your FormArray or Array.

const CarsList = [
  { name: 'Mercedes' },
  { name: 'BMW' },
  { name: 'Porsche' },
  { name: 'Cadillac' }
];
const result = CarsList.filter(s => s.name.includes('Mercedes'));

console.log(result);
Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42