If you want to retrieve the current value of a select element, follow these steps:
<!-- HTML TEMPLATE -->
<select [(ngModel)]="selectedDevice">
<option [ngValue]="null">Select device</option>
<option *ngFor="let device of devices" [ngValue]="device">
Name: {{ device.name }} -
Address: {{ device.address }} -
Class: {{ device.class }}
<br>
</option>
</select>
Use
[(ngModel)]="selectedDevice"
to access the selected device from the select element.
Then utilize
[ngValue]
in the options to pass the selected object.
[value]="..."
only works with string values
[ngValue]="..."
supports any data type
In your Typescript file, create a property for the selectedDevice
.
import { Component } from '@angular/core';
import { BluetoothDevice } from '@app-models/bluetooth-device'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor() { }
selectedDevice: BluetoothDevice | null = null;
}
Don't forget to include the FormsModule
in the imports array of your working module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Required for ngModel to function.
// Components
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
],
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
You should now be all set. You can remove the selectDevice
function and directly access the selected device by referencing the selectedDevice
property.
import { Component } from '@angular/core';
import { BluetoothDevice } from '@app-models/bluetooth-device'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor() { }
selectedDevice: BluetoothDevice | null = null;
onSumbit() {
if (!this.selectedDevice) {
console.log('No device selected');
return;
}
console.log('Device selected: ', this.selectedDevice);
}
}