-1

I'm new to Angular and I have a selection that on its option selection I want to change the route

now I want to change the route exactly after selecting one of the options, not by pressing entr after selection! any body can help?

<input type="text" name="" value="" class="form-control" matInput [formControl]="searchControl" [matAutocomplete]="auto" (change)="searchComponent($event)">
                <button class="search-btn"><fa-icon icon="search" class="fa-icon"></fa-icon></button>
                <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" class="animated fadeIn">
                    <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
                        <a routerLink="/{{option.url}}">
                            {{option.name}}
                            {{option.id}}
                        </a>
                    </mat-option>
                </mat-autocomplete>

as you see I have used (change) to get the value and I do! but after selecting the option the value is displayed in the input and it works after pressing enter! but I want it to work without enter.

HannaAB
  • 23
  • 8
  • Possible duplicate of [Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?](https://stackoverflow.com/questions/39501595/angular-2-select-option-dropdown-how-to-get-the-value-on-change-so-it-can-be) – j4rey Jan 28 '19 at 12:00

3 Answers3

0

You can't listen to click events of option. The event doesn't fire in all browsers (the only browsers it works in is < ie11 and Firefox)

You can use

<select ngModel (ngModelChange)="mySelectHandler($event)">
  <option *ngFor="let value of options" [ngValue]="value">{{value.text}}</option>
</select>

to execute code after an option was selected.

0
  <select [value]="myVal" (change)="changeRoute($event.target.value)">
     <option value="">Select Value</option>
     <option *ngFor="let obj of temp" [value]="obj">{{obj}}</option>
   </select>

in Change event you can trigger the select option change and you can write your route logic in changeRoute function

Kajol Chaudhary
  • 257
  • 2
  • 9
0

I found the solution!

 <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" class="animated fadeIn" (optionSelected)="searchComponent($event)">
                <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
                    <a routerLink="/{{option.url}}">
                        {{option.name}}
                        {{option.id}}
                    </a>
                </mat-option>
            </mat-autocomplete>

and in the searchComponent function:

searchComponent(event: MatAutocompleteSelectedEvent){
    console.log(event.option.value);
}

this way I get the mat-option value on selection!

HannaAB
  • 23
  • 8