#How can I console.log the selected option from a form-select bootstrap

7 messages · Page 1 of 1 (latest)

sly coral
#

I try to console.log the value selected in my ts fil like this :

  changeLanguage(language: string) {
    console.log(language);
  }

i have a nav.component.html

            <select class="form-select" aria-label="Default select example" (change)="changeLanguage($event!.target.value)">
                <option value="fr" selected>Français</option>
                <option value="an">Anglais</option>
                <option value="es">Espagnol</option>
            </select>

but this give the error :

Property 'value' does not exist on type 'EventTarget'.

solid hull
#

You will have to cast it ,to get the correct target (e.g. the select element).

  changeLanguage(event: Event) {
    const target = event.target as HTMLSelectElement;
    console.log(target.value);
  }
keen pilot
#

target type is defined as EventTarget | null you could simply add ! after target or ? and handle empty values in changeLanguage arguments accordingly:

<select class="form-select" aria-label="Default select example" (change)="changeLanguage($event!.target!.value)">
sly coral
#
<select class="form-select" aria-label="Default select example" (change)="changeLanguage($event!.target!.value)">
  changeLanguage(event: Event) {
    const target = event.target as HTMLSelectElement;
    console.log(target.value);
  }

And i steel have the same error

solid hull
#

just pass in the $event in the template. You can't get the value in the template because the type there is EventTarget

sly coral
#

thanks you ! 👍🙂

keen pilot
#

Ah, indeed EventTarget doesn't have value 👍