Html 将选择元素绑定到 Angular 中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35945001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding select element to object in Angular
提问by RHarris
I'd like to bind a select element to a list of objects -- which is easy enough:
我想将一个 select 元素绑定到一个对象列表——这很容易:
@Component({
selector: 'myApp',
template: `<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" value="c.id">{{c.name}}</option>
</select>`
})
export class AppComponent{
countries = [
{id: 1, name: "United States"},
{id: 2, name: "Australia"}
{id: 3, name: "Canada"},
{id: 4, name: "Brazil"},
{id: 5, name: "England"}
];
selectedValue = null;
}
In this case, it appears that selectedValuewould be a number -- the id of the selected item.
在这种情况下,它似乎selectedValue是一个数字——所选项目的 id。
However, I'd actually like to bind to the country object itself so that selectedValueis the object rather than just the id. I tried changing the value of the option like so:
但是,我实际上想绑定到 country 对象本身,以便它selectedValue是对象而不仅仅是 id。我尝试像这样更改选项的值:
<option *ngFor="#c of countries" value="c">{{c.name}}</option>
but this does not seem to work. It seems to place an object in my selectedValue-- but not the object that I'm expecting. You can see this in my Plunker example.
但这似乎不起作用。它似乎将一个对象放在我的selectedValue- 但不是我期望的对象中。您可以在我的 Plunker 示例中看到这一点。
I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated -- meaning I don't have access to the newly selected value at that point.
我还尝试绑定到更改事件,以便我可以根据选定的 id 自己设置对象;但是,似乎在更新绑定的 ngModel 之前触发了更改事件——这意味着我当时无法访问新选择的值。
Is there a clean way to bind a select element to an object with Angular 2?
有没有一种干净的方法将选择元素绑定到带有 Angular 2 的对象?
回答by Günter Z?chbauer
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>
NOTE: you can use [ngValue]="c"instead of [ngValue]="c.id"where c is the complete country object.
注意:您可以使用[ngValue]="c"代替[ngValue]="c.id"where c 是完整的国家/地区对象。
[value]="..."only supports string values[ngValue]="..."supports any type
[value]="..."只支持字符串值[ngValue]="..."支持任何类型
update
更新
If the valueis an object, the preselected instance needs to be identical with one of the values.
如果value是对象,则预选实例需要与其中一个值相同。
See also the recently added custom comparison https://github.com/angular/angular/issues/13268available since 4.0.0-beta.7
另请参阅最近添加的自定义比较https://github.com/angular/angular/issues/13268自 4.0.0-beta.7 起可用
<select [compareWith]="compareFn" ...
Take care of if you want to access thiswithin compareFn.
如果您想this在compareFn.
compareFn = this._compareFn.bind(this);
// or
// compareFn = (a, b) => this._compareFn(a, b);
_compareFn(a, b) {
// Handle compare logic (eg check if unique ids are the same)
return a.id === b.id;
}
回答by Carolina Faedo
This could help:
这可以帮助:
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" [value]="c.id">{{c.name}}</option>
</select>
回答by Rahul Kumar
You can do this too without the need to use [(ngModel)]in your <select>tag
您也可以这样做,而无需[(ngModel)]在您的<select>标签中使用
Declare a variable in your ts file
在 ts 文件中声明一个变量
toStr = JSON.stringify;
toStr = JSON.stringify;
and in you template do this
并在您的模板中执行此操作
<option *ngFor="let v of values;" [value]="toStr(v)">
{{v}}
</option>
and then use
然后使用
let value=JSON.parse(event.target.value)
to parse the string back into a valid JavaScript object
将字符串解析回有效的 JavaScript 对象
回答by Jose Carlos Ramos Carmenates
It worked for me:
它对我有用:
Template HTML:
模板 HTML:
I added (ngModelChange)="selectChange($event)"to my select.
我添加(ngModelChange)="selectChange($event)"到我的select.
<div>
<label for="myListOptions">My List Options</label>
<select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
在 component.ts 上:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.tsthis function:
您需要添加component.ts到此功能:
selectChange( $event) {
//In my case $event come with a id value
this.model.myListOptions = this.listOptions[$event];
}
Note:
I try with [select]="oneOption.id==model.myListOptions.id"and not work.
注意:我尝试使用[select]="oneOption.id==model.myListOptions.id"但不起作用。
============= Another ways can be: =========
============ 另一种方式可以是: ==========
Template HTML:
模板 HTML:
I added [compareWith]="compareByOptionIdto my select.
我添加[compareWith]="compareByOptionId到我的select.
<div>
<label for="myListOptions">My List Options</label>
<select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
在 component.ts 上:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.tsthis function:
您需要添加component.ts到此功能:
/* Return true or false if it is the selected */
compareByOptionId(idFist, idSecond) {
return idFist && idSecond && idFist.id == idSecond.id;
}
回答by elvin
Just in case someone is looking to do the same using Reactive Forms:
以防万一有人希望使用 Reactive Forms 做同样的事情:
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
</select>
<p>Selected Country: {{country?.name}}</p>
</form>
Check the working example here
在此处检查工作示例
回答by Eng.Gabr
You Can Select the Id using a Function
您可以使用函数选择 ID
<option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option>
回答by Shubhranshu
For me its working like this, you can console event.target.value.
对我来说它是这样工作的,你可以控制台event.target.value。
<select (change) = "ChangeValue($event)" (ngModel)="opt">
<option *ngFor=" let opt of titleArr" [value]="opt"></option>
</select>
回答by nikola.maksimovic
Also, if nothing else from given solutions doesn't work, check if you imported "FormsModule" inside of "AppModule", that was a key for me.
另外,如果给定解决方案中的任何其他内容都不起作用,请检查您是否在“AppModule”中导入了“FormsModule”,这对我来说很重要。
回答by Rafi
Create another getter for selected item
为所选项目创建另一个 getter
<form [formGroup]="countryForm">
<select formControlName="country">
<option *ngFor="let c of countries" [value]="c.id">{{c.name}}</option>
</select>
<p>Selected Country: {{selectedCountry?.name}}</p>
</form>
In ts :
在 ts 中:
get selectedCountry(){
let countryId = this.countryForm.controls.country.value;
let selected = this.countries.find(c=> c.id == countryId);
return selected;
}
回答by Jose Kj
You can get selected value also with help of click() by passing the selected value through the function
您也可以在 click() 的帮助下通过函数传递选定的值来获取选定的值
<md-select placeholder="Select Categorie"
name="Select Categorie" >
<md-option *ngFor="let list of categ" [value]="list.value" (click)="sub_cat(list.category_id)" >
{{ list.category }}
</md-option>
</md-select>

