0

I need to update the added value in the DOM. I pushing a new element into the array(options). But it's not updating in the DOM.

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css'],
})
export class AutocompleteFilterExample implements OnInit {
  myControl = new FormControl();
  options: string[] = ['One', 'Two', 'Three'];
  filteredOptions: Observable<string[]>;

 ngOnInit() {
  this.filteredOptions = this.myControl.valueChanges.pipe(
    startWith(''),
    map((value) => this._filter(value))
  );
 }

  private _filter(value: string): string[] {
  const filterValue = value.toLowerCase();

  return this.options.filter((option) =>
   option.toLowerCase().includes(filterValue)
  );
 }

 addOption() {
  this.options.push('Four');
 }
}

stackblitz link

enter image description here

Shankar
  • 2,565
  • 8
  • 29
  • 56

2 Answers2

0

Here's a stackblitz which automatically updates your options when clicking the "add" button.

The approach is that your filteredOptions$ (per convention, Observables end with a $) are based on two Observable streams:

  • Once, the search field input
  • Second, the options as an Observable stream which gets updated when the button is clicked
0

options is used to filter the user's input, so the user needs to start typing something first to see the new added option in the autocomplete.

What you are missing is to refill the filteredOptions with options once the new value "Four" has been added.

  addOption() {
    this.options.push('Four');
    this.filteredOptions = of(this.options);
  }
Andres2142
  • 2,622
  • 2
  • 14
  • 19