我是角色2的新手。
我有以下代码段。
<select name="shape_id" (change)="changeShape()">
<option *ngFor="let shape of shapes" [ngValue]="shape.name">
{{shape.name}}
</option>
</select>
在选择选项时,我想将所选形状id的值设置为我的组件中名为shapeId的属性。
形状看起来很糟糕
[{ “名称”: “AA”, “ID” 为 “1”},{ “名称”: “BB”, “ID”: “3”},{ “名称”: “CC”,” ID “:” 2" }]
任何人都可以帮助我。
答案 0 :(得分:0)
<select name="shape_id" (change)="changeShape($event.target.value)"> // add this to change method
<option *ngFor="let shape of shapes" [ngValue]="shape.id">
{{shape.name}}
</option>
</select>
在组件
中value : string;
changeShape(selectedValue : string){
this.value = selectedValue;
}
或者你可以选择其中任何一种工作
<select name="shape_id" [(ngModel)]="selectedVal"> // use ngModel here
<option *ngFor="let shape of shapes" [ngValue]="shape.id">
{{shape.name}}
</option>
</select>
此selectedVal将是Component
中的变量评论后更新
<select name="shape_id" (change)="changeShape(i)"> // add this to change method
<option *ngFor="let shape of shapes;let i = index" [ngValue]="shape.id">
{{shape.name}}
</option>
</select>
传递索引值,然后您可以在组件中查找ID并将selectedvalue
更改为selected index : number
答案 1 :(得分:0)
此解决方案将所选对象本身绑定到组件属性,您可以根据需要在事件处理程序中处理所选形状。
代码段:
让我们先说明结构:
interface Shape {
name: string;
id: number;
}
模板代码:
<select (change)="changeShape()" [(ngModel)]="selectedShape">
<option *ngFor="let shape of shapes" [ngValue]="shape">
{{shape.name}}
</option>
</select>
<p>selected shape: {{shapeName}}</p>
组件代码:
private selectedShape: Shape;
private shapes : Shape[] = [
{name: "circle", id: 0},
{name: "rectangle", id: 1}
];
private shapeName: string;
public changeShape() {
this.shapeName = this.selectedShape.name;
}
答案 2 :(得分:0)
-
<select name="shape_id" (change)="changeShape($event.target.value)">
<option *ngFor="let shape of shapes" [value]="shape.id">
{{shape.name}}
</option>
</select>
在你的组件中 -
shapeId: string;
changeShape(id: string) {
this.shapeId = id;
}