0
votes

how are you? I have one problem 'slice' of undefined in my project. I use autocomplete material https://material.angular.io/components/autocomplete/examples

My code.ts //get all Country from webservice

this.ws.AllCountry().subscribe(
      countryes => {
        this.countryes = countryes.map((country) => {
          return new Country(country);
        });
      }
    );

// Create FilterOptions

   this.stateCtrl = new FormControl();
    this.filteredOptionsCountry = this.stateCtrl.valueChanges
      .pipe(
      startWith(''),
      map(country =>  country ? this.filterCountry(country) : this.countryes.slice()) // Cannot read property 'slice' of undefined
    );

// filter country

 filterCountry(name: string) {
    return this.countryes.filter(country =>
      country.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
  }

Code.html

 <form class="example-form">
     <mat-form-field class="example-full-width">
     <input matInput placeholder="Select Country" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
       <mat-autocomplete #auto="matAutocomplete">
         <mat-option *ngFor="let country of filteredOptionsCountry | async" [value]="country.country_id">
           {{ country.name }}
         </mat-option>
       </mat-autocomplete>
     </mat-form-field>
   </form>

Can you suggest me some idea, what is the problem?

Thank you

2
The message is telling where the error is... countryes is apparently undefined, you need to debug your code ;)AJT82
if you can reproduce this would be easy in like stackblitz or somethingRahul Singh
slice() is equal to slice(0)Fateh Mohamed

2 Answers

0
votes

i think you're using countryes before it's defined inside subscription, i suggest to move your "Create FilterOptions" code inside allCountry subscription where countryes is defined

0
votes

Try this...

map((country: string | null) => country ? this._filter(country) : this.countryes.slice()));