To get the current value of the select do the following:
<!-- HTML TEMPLATE -->
<select [(ngModel)]="selectedDeviced">
<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>
You need [(ngModel)]="selectedDeviced"
to access to the selected device from the select.
Then use [ngValue]
in the options to pass the the object selected.
[value]="..."
only supports string values
[ngValue]="..."
supports any type
And in the Typescript create the 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;
}
Finally don't forget to add the FormsModule
to the imports array in the module you are working on.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import to allow ngModel to work.
// Components
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
],
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
And boom, it should be working. You can now get rid of the function selectDevice
and to access to the selected device, you do it be 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);
}
}