Search code examples
angularangular-ngselect

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.


Solution

  • 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