Reputation: 5058
I need to get the selected item in a select property. This is how I get it
<div class="form-group">
<label>Plaza</label>
<select
formControlName="plaza"
class="browser-default custom-select mb-4"
(change)="onPlazaChange($event)"
>
<option value="" disabled>Plaza</option>
<option
*ngFor="let plaza of plazas"
[ngValue]="plaza"
>{{plaza.name}}</option>
</select>
</div>
onPlazaChange(event: any) {
console.log(event.target.value);
}
export class Plaza {
id?: string;
name: string;
code: number;
lanes: Lane[];
}
export class Lane {
number: number;
type: string;
}
I don't know what's wrong but I should get the object plaza not just the id alone. All I get is "Object".
Upvotes: 0
Views: 54
Reputation: 722
[value]="plaza" is always a string to get object you have to use [ngValue]="plaza"
Here is a stackblitz https://stackblitz.com/edit/angular-hy1xw9?file=app/app.component.html where the 1st one is incorrect and second is correct
You can use ngModel to get the value, I am not sure why it is not showing the details with event.target.value.
<h3>Using <code>ngValue</code></h3>
<select [(ngModel)]="selectedNode" (change)="onNodeChange()" >
<option [ngValue]="null">All nodes</option>
<option *ngFor="let node of nodes" [ngValue]="node">
{{ node.id }} - {{ node.name }}
</option>
</select>
onNodeChange() {
console.log( JSON.stringify(this.selectedNode));
}
https://stackblitz.com/edit/angular-oyn97w
Upvotes: 1
Reputation: 6016
select
dropdown is to get the checked value not recommended to get complete the Object.
So get the Id
of the object and compare it in the TS file to filter it.
Template :
<select formControlName="plaza"
class="browser-default custom-select mb-4"
(change)="onPlazaChange($event)"
>
<option value="" disabled>Plaza</option>
<option
*ngFor="let plaza of plazas"
[value]="plaza.id"
>{{plaza.name}}</option>
</select>
Ts:
onPlazaChange(event: any) {
console.log(event.target.value);
const id = event.target.value;
const selectedPlaza = this.plazas.filter(plaza => plaza.id == id);
}
P.S : don't use
ngModelChange
andchange
in select tag(onlychange
is enough)
hope this helps.. ;)
Upvotes: 1