javascript - Angular 9 选择绑定到模型
问题描述
在我开始之前,我尝试了以下
https://www.angularjswiki.com/angular/how-to-bind-a-select-element-to-object-in-angular/ https://www.codeproject.com/Questions/1278097/How-do- you-get-the-value-of-the-selected-option-in将 选择值关联到 Angular 4 中的 ngModel 当值是 Angular 2 中的类对象时如何将选定值分配给“选择” _https ://docs。 angularjs.org/api/ng/directive/select
用 PHP 做这么简单的事情花了我 8 个小时,但我还没有接近。我不明白我在这里做错了什么?
TS文件
shopstates: any = {};
selectedObject: any;
this.shopstates = [
{ statename: 'Australian Capital Territory', statecode: 'ACT' },
{ statename: 'New South Wales', statecode: 'NSW' },
{ statename: 'South Australia', statecode: 'SA' },
{ statename: 'Queensland', statecode: 'QLD' }
];
组件 html 文件
<select [(ngModel)]="selectedObject" class="form-control" (change)=consoleLog()>
<option *ngFor="let state of shopstates" [ngValue]="state">{{ state.statename }} ({{ state.statecode }})</option>
</select>
选定状态为 {{ selectedObject.state }}
这非常令人沮丧。我即将进行更改以尝试将值传递给 TS 文件,但我不想这样做并且 2. 无论如何都不知道如何传递值
任何方向或帮助表示赞赏
解决方案
您可以尝试如下。
selectedObject
在选择的更改事件上传递给consoleLog(selectedObject)
方法。selectedObject
保存整个状态对象,因此您无法访问 likeselectedObject.state
。应该是selectedObject.statename
/selectedObject.statecode
工作堆栈闪电战
模板
<select [(ngModel)]="selectedObject" class="form-control" (change)="consoleLog(selectedObject)">
<option *ngFor="let state of shopstates" [ngValue]="state">{{ state.statename }} ({{ state.statecode }})</option>
</select>
<div>
<p><b>Selected state Name : </b> {{ selectedObject.statename }}</p>
<p><b>Selected state Code : </b> {{ selectedObject.statecode }}</p>
</div>
打字稿
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
shopstates = [{
statename: "Australian Capital Territory",
statecode: "ACT"
},
{
statename: "New South Wales",
statecode: "NSW"
},
{
statename: "South Australia",
statecode: "SA"
},
{
statename: "Queensland",
statecode: "QLD"
}
];
selectedObject: any = this.shopstates[0];
consoleLog(statename) {
console.log(statename);
}
}
推荐阅读
- unity3d - 如何根据头部位置、旋转、注视原点和方向找到用户在 Unity 场景中的位置?
- javascript - UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“get”
- java - 使用 gson 在内部将对象存储为 json 是常见的做法吗?
- pandas - 如何在熊猫数据框中使用字段“ID”作为索引并在读取 xls 文件时跳过一行?
- dart - 如何在时间范围内获取键盘用户输入
- reactjs - 在运行时创建 redux 导出
- javascript - 如何从另一个 html 文件中取消隐藏元素 onclick
- emacs - 如何删除emacs full?
- gnuplot - 如何正确地将透视图添加到代表分子的 Gnuplot 3D 连接点云?
- c# - 哈希集
包含重复项