skip to Main Content

I am beginner webdeveloper. I have this code:

<input id="street{{sid}}" 
       name="street{{sid}}" 
       type="text" 
       placeholder="" 
       class="form-control"
       [(ngModel)]="adres.street" 
       #street="ngModel" 
       required="" 
       (keydown)="this.removeSpecialCharactersFromStreet($event)"
       (keyup)="this.removeSpecialCharactersFromStreet($event)"
       capitalize-first="true">
removeSpecialCharactersFromStreet(event) {
  this.adres.street = event.target.value.replace(/[&/\#,+()$~%.]'":*?<>{}@^&=;'"_![]/g, '');
}

and it works fine.

Now I need to add this function to mat-autocomplete:

removeSpecialCharactersFromCity(event) {
  this.adres.city = event.target.value.replace(/[&/\#,+()$~%.]'":*?<>{}@^&=;'"_![]/g, '');
}
<mat-autocomplete 
       autoActiveFirstOption 
       #auto="matAutocomplete"
       (keydown)="this.removeSpecialCharactersFromCity($event)" 
       (keyup)="this.removeSpecialCharactersFromCity($event)">
  <mat-option *ngFor="let option of cityFilteredOptions" 
              [value]="option"
              (keydown)="this.removeSpecialCharactersFromCity($event)" 
              (keyup)="this.removeSpecialCharactersFromCity($event)">
    {{option}}
  </mat-option>
</mat-autocomplete>

And it doesn’t work.
How can I fix it?

Please help me

2

Answers


  1. Change the (keydown) and (keyup) event bindings on mat-autocomplete to (input) event binding.

    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (input)="removeSpecialCharactersFromCity($event)">
      <mat-option *ngFor="let option of cityFilteredOptions" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
    

    Update the removeSpecialCharactersFromCity function to use the event object directly.

    removeSpecialCharactersFromCity(event: any) {
      this.adres.city = event.target.value.replace(/[&/\#,+()$~%.]'":*?<>{}@^&=;'"_![]/g, '');
    }
    

    Edit:

    Change

    (input)="removeSpecialCharactersFromCity($event)"
    

    to

    (input)="removeSpecialCharactersFromCity($event.target.value)
    
    Login or Signup to reply.
  2. You can connect autocomplete to your own input and then manipulate the input value as you did to the regular input:

    <input
      matInput
      [(ngModel)]="address.city"
      [matAutocomplete]="auto"
      (keydown)="removeSpecialCharactersFromCity($event)"
      (keyup)="removeSpecialCharactersFromCity($event)">
    
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let option of cityFilteredOptions" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
    

    Working example in stackblitz

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search