我需要在select属性中获取所选项目。这就是我的方法
<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;
}
我不知道出了什么问题,但我应该获得对象广场,而不仅仅是ID。我得到的只是“对象”。你能帮忙吗?谢谢。
答案 0 :(得分:1)
[value] =“ plaza”始终是一个字符串,您必须使用[ngValue] =“ plaza”
这是一堆https://stackblitz.com/edit/angular-hy1xw9?file=app/app.component.html 第一个不正确,第二个是正确的
您可以使用ngModel来获取值,我不确定为什么它没有显示带有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));
}
答案 1 :(得分:1)
select
下拉列表用于获取不建议使用的检查值,以完成对象。
因此,获得对象的 Id
并将其与TS文件进行比较以对其进行过滤。
模板:
<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);
}
PS:不要在选择代码中使用
ngModelChange
和change
(仅change
即可)
希望这会有所帮助..;)