Danyx
Danyx

Reputation: 724

ng-select prevent special characters on typeahead

Using the ng-select library, is is possible to prevent special characters from being processed? Something akin to this solution.

I've tried multiple approaches, but it seems like whatever the typeahead value is isn't exposed and can't be modified.

Is there any workaround to this? Even firing a .next() on the typeahead subject doesn't change what's shown on the view.

Upvotes: 2

Views: 2556

Answers (2)

Barremian
Barremian

Reputation: 31125

By special characters, I assume you mean all non-numeric and non-alphabetic characters. In that case, you could strip the special characters before it is used for filtering using a simple regex like searchTerm = searchTerm.replace(/[^a-zA-Z0-9 ]/g, "");.

A simple Stackblitz.

Template:

<h5>Select:</h5>
<ng-select [items]="items$ | async"
  bindLabel="name"
  bindValue="name"
  [closeOnSelect]="true"
  [multiple]="true"
  [hideSelected]="true"
  [typeahead]="input$">
</ng-select>

Component:

export class AppComponent  {
  public items$: Observable<Person[]>;
  public input$ = new Subject<string | null>();

  constructor() {
    this.input$.subscribe((typeahead) => {
      console.log(typeahead);
    });

    this.items$ = this.input$.pipe(
      map((term) => this.searchPeople(term))
    )
  }

  private searchPeople(term: string | null): Person[] {
    let searchTerm = term ? term : '';
    searchTerm = searchTerm.replace(/[^a-zA-Z0-9 ]/g, "");
    return [
      { name: 'Jack Doe' },
      { name: 'Jonathan Hammond' },
      { name: 'Lindsay Johann' },
    ].filter((person) => {
      return person.name.toLowerCase().startsWith(searchTerm.toLowerCase());
    });
  }
}

Notice that only one empty space character is included (after 0-9). So if there are more than one, the filter will fail and there will no suggestions.

Example: Typing jona!@#$%^&than hamm*}|"ond would still suggest Jonathan Hammond. However, typing jona!@#$%^ &than hamm*}|"ond (notice space between ^ and &) wouldn't suggest anything.

Sample application forked from here.

Upvotes: 0

Oussail
Oussail

Reputation: 2288

If i understand you want to block special characters from being typed and you don't want to see them at all.

Answer :

Yes you can prevent special characters from being processed by using keypress event handler as shown below.

HTML :

<ng-select name="languages" (keypress)="blockSpecialChars($event)" placeholder="languages" [items]="suggestionsList" [typeahead]="typeahead" [(ngModel)]="currentValue" >

That's what you want : (keypress)="blockSpecialChars($event)"

Add into your Typescript :

  blockSpecialChars(event) {   
      var k;  
      k = event.charCode;
      return((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57)); 
  }

If you want to allow some special characters and you don't know what is there charCode. check it here : KeyCode info

Upvotes: 2

Related Questions