Home > other >  How to get value from <select><option> dropdown menu in Angular?
How to get value from <select><option> dropdown menu in Angular?

Time:04-09

I made a dropdown menu. I want to dynamically set the default value. When the user changes the value I want a method to fire in the component controller and log the new value.

This dynamically sets the default value and shows all of the options. When the user changes the option the method onChange() fires. The problem is that the method logs the <select>, not the <option>.

<form>
   <select (change)="onChange($event.target)" style="padding: 10px; font-size: 12pt;">
       <option *ngFor="let number of numbers" [selected]="number==clipInMovieWatching">Watch clip: {{number}}</option>
   </select>
</form>
onChange(event: any) {
    console.log(event);
}

Result logged:

<select _ngcontent-keh-c129 style=​"padding:​ 10px;​ font-size:​ 12pt;​">​…​</select>​

All of the options are logged, not the option that the user selected.

console.log(event.target) logs undefined.

console.log(event.target.target) throws an error Cannot read properties of undefined (reading 'value').

I tried using Material mat-select:

<mat-form-field>
   <mat-select>
      <mat-option (onSelectionChange)="selectClip($event)" *ngFor="let number of numbers" [value]="number">Watch clip: {{number}}</mat-option>
   </mat-select>
</mat-form-field>
selectClip(event: any) {
    console.log(event.source.value);
}

This logs the option that the user selected. But the dropdown menu doesn't show the default option. The documentation shows a property selected:

selected: MatOption | MatOption[]

The currently selected option.

but I can't get it to work.

Also, mat-select shows only four options. How can I make it show all the options?

CodePudding user response:

Try

console.log(event.target.value);

CodePudding user response:

The mistake was that in the HTML view I had (change)="onChange($event.target) or (change)="onChange($event.target.value). That throws the undefined error. The correct code is (change)="onChange($event)". Then in the controller console.log(event.target.value);.

<form>
   <select (change)="onChange($event)" style="padding: 10px; font-size: 12pt;">
       <option *ngFor="let number of numbers" [value]="number" [selected]="number==clipInMovieWatching">Watch clip: {{number}}</option>
   </select>
</form>
onChange(event: any) {
  console.log(event.target.value);
}

[value]="number" helps but isn't essential. Without this it logs Watch clip: 14. With this code it logs 14.

  • Related