首页 > 解决方案 > 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. 无论如何都不知道如何传递值

任何方向或帮助表示赞赏

标签: javascriptangulartypescriptselect

解决方案


您可以尝试如下。

  • selectedObject在选择的更改事件上传递给consoleLog(selectedObject)方法。
  • selectedObject保存整个状态对象,因此您无法访问 like selectedObject.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);
  }
}

推荐阅读