Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将值映射到角度2中的id_Angular_Angular2 Forms - Fatal编程技术网

Angular 将值映射到角度2中的id

Angular 将值映射到角度2中的id,angular,angular2-forms,Angular,Angular2 Forms,我的代码看起来像 <select [(ngModel)]=""> <option value="1">New York</option> <option value="2"Phoenix</option> <option value="3">Boston</option>

我的代码看起来像

<select [(ngModel)]="">
                    <option value="1">New York</option>
                    <option value="2"Phoenix</option>
                    <option value="3">Boston</option>
                </select>

纽约
[(ngModel)]
绑定可以绑定到组件上的任何属性。然后,您可以在组件上执行的方法中引用该属性,以提交给远程资源,如RESTfulAPI或类似的资源

对于
下拉列表,
[(ngModel)]
将绑定到给定
的select
属性。只需在类上创建一个属性,例如
cityId:number
并将其放入
[(ngModel)]=“cityId”
中。然后通过
this.cityId
引用方法中的
cityId
,您可以将其发送到API/数据库或任何需要的地方。您可以通过更新
cityId
属性数值(如
this.cityId=2
)来设置下拉列表的值,视图中的
将相应更新

下面是一个人为的示例和一个演示功能的示例。我建议将模板放在一个单独的文件中。如果没有关于表单、模型和应用程序结构的附加信息,很难准确地看到您需要什么

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <select [(ngModel)]="cityId">
        <option value="-1">Select city...</option>
        <option value="1">New York</option>
        <option value="2">Phoenix</option>
        <option value="3">Boston</option>
    </select>

    <br />

    <div>Select City Id: {{cityId}}</div>

    <br />

    <button type="button" (click)="doSomethingWithCityValues()">Click Me</button>

    <br />
    <br />

    <button type="button" (click)="setCityValue()">Click Me</button>
  `
})
export class AppComponent {
   cityId: number = -1;

   doSomethingWithCityValues() {
     // you can use cityId value via this.cityId
     console.log(this.cityId);
   }

   setCityValue() {
     this.cityId = Math.floor(Math.random() * 3) + 1;
   }
}
从'@angular/core'导入{Component};
@组成部分({
选择器:“我的应用程序”,
模板:`
选择城市。。。
纽约
凤凰
波士顿

选择城市Id:{{cityId}
点击我

点击我 ` }) 导出类AppComponent{ cityId:number=-1; doSomethingWithCityValues(){ //您可以通过this.cityId使用cityId值 console.log(this.cityId); } setCityValue(){ this.cityId=Math.floor(Math.random()*3)+1; } }

希望这有帮助

当组件加载时,是否会从REST API之类的东西中获取城市项目的集合/数组/列表?对于要显示的每个城市,该组件都具有数字id和字符串文本值?否。这些值总是硬编码在HTML上。他们不会改变