我有一个下拉列表,其中包含来自循环的几个选项,我需要单击按钮来获取选定的选项(不是值)。我尝试过,ngModel
但我能够获得价值,而不是选择。谁能帮帮我吗?这是下面的代码
<div>
<select>
<option *ngFor="let group of groups" value="{{group.id}}">{{group.name}}</option>
</select>
</div>
<input type="button" (click)="getVal()" value="submit"/>
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
ngOnInit() {
}
getVal() {
}
groups = [{
"id": 1,
"name": "pencils",
"items": "red pencil"
},
{
"id": 2,
"name": "rubbers",
"items": "big rubber"
},
{
"id": 3,
"name": "rubbers1",
"items": "big rubber1"
}];
}
仅用于ngModel
绑定到选定的值。由于您希望从所选选项中获取id
和name
,因此最好获取所选的整个对象。您可以使用ngValue
(来源:docs)来做到这一点。
<select [(ngModel)]="selectedGroup">
<option *ngFor="let group of groups" [ngValue]="group">{{group.name}}</option>
</select>
selectedGroup: any;
getVal() {
console.log(this.selectedGroup); // returns selected object
console.log(this.selectedGroup.id); // returns selected option's id
console.log(this.selectedGroup.name); // returns selected option's name
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句