Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

trifek's avatar

String replace in mat-autocomplete in Angular

Hi. 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, '');
      }

abd it's work fine :)

Now i need 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's not work :( How can i repair it?

Please help me

0 likes
2 replies
Amywood's avatar

Hello, In your code, the event object in the removeSpecialCharactersFromCity function is not the same as the one in the input element's event handlers. In the input element, you're using event.target.value to access the input's value, but in the autocomplete, event.target.value doesn't work because the event target is not the input element.

To fix this issue, you can modify your code as follows: https://www.myaccountaccess.one/

Pass the value directly to the removeSpecialCharactersFromCity function in the autocomplete's event handlers, instead of passing the entire event object. <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (keydown)="removeSpecialCharactersFromCity($event.target.value)" (keyup)="removeSpecialCharactersFromCity($event.target.value)"> <mat-option ngFor="let option of cityFilteredOptions" [value]="option" (keydown)="removeSpecialCharactersFromCity($event.target.value)" (keyup)="removeSpecialCharactersFromCity($event.target.value)"> {{option}} Modify the removeSpecialCharactersFromCity function to accept the value as a parameter and perform the replace operation. removeSpecialCharactersFromCity(value: string) { this.adres.city = value.replace(/[&/#,+()$~%.]'":?<>{}@^&=;'"_![]/g, ''); } With these changes, the removeSpecialCharactersFromCity function will correctly replace the special characters in the city value when triggered by the autocomplete events.

Please or to participate in this conversation.