typescript – 如何在Angular2中的对象数组上使用select / optio
发布时间:2020-12-17 07:06:24 所属栏目:安全 来源:网络整理
导读:参见英文答案 Binding select element to object in Angular????????????????????????????????????10个 我在Angular2中创建一个由Object数组而不是字符串支持的选择时遇到了麻烦.我知道如何使用 ngOptions在AngularJS中执行此操作,但它似乎不适用于Angular2(
参见英文答案 >
Binding select element to object in Angular????????????????????????????????????10个
我在Angular2中创建一个由Object数组而不是字符串支持的选择时遇到了麻烦.我知道如何使用 ngOptions在AngularJS中执行此操作,但它似乎不适用于Angular2(我使用的是alpha 42). 在下面的示例中,我有四个选择,但只有两个选择. >’Select String’是一个简单的基于字符串的选择,它工作正常. 如果这是预期的方式,我可以做#4,但它看起来很笨重.还有另一种方法吗?我是不是太早了?我做了些傻事吗? import {Component,FORM_DIRECTIVES,NgFor} from 'angular2/angular2'; interface TestObject { name:string; value:number; } @Component({ selector: 'app',template: ` <h4>Select String</h4> <select [(ng-model)]="strValue"> <option *ng-for="#o of strArray" [value]="o">{{o}}</option> </select> <h4>Select Object via 2-way binding</h4> <select [(ng-model)]="objValue1"> <option *ng-for="#o of objArray" [value]="o">{{o.name}}</option> </select> <h4>Select Object via event</h4> <select [ng-model]="objValue2" (change)="updateObjValue2($event)"> <option *ng-for="#o of objArray" [value]="o">{{o.name}}</option> </select> <h4>Select Object via string</h4> <select [ng-model]="objValue3.name" (change)="updateObjValue3($event)"> <option *ng-for="#o of strArray" [value]="o">{{o}}</option> </select> <div><button (click)="printValues()">Print Values</button></div> `,directives: [FORM_DIRECTIVES,NgFor] }) export class AppComponent { objArray:TestObject[] = [{name: 'foo',value: 1},{name: 'bar',value: 1}]; objValue1:TestObject = this.objArray[1]; objValue2:TestObject = this.objArray[1]; objValue3:TestObject = this.objArray[1]; strArray:string[] = this.objArray.map((obj:TestObject) => obj.name); strValue:string = this.strArray[1]; updateObjValue2(event:Event):void { const value:string = (<HTMLSelectElement>event.srcElement).value; this.objValue2 = this.objArray.find((obj:TestObject) => obj.name === value); } updateObjValue3(event:Event):void { const value:string = (<HTMLSelectElement>event.srcElement).value; this.objValue3 = this.objArray.find((obj:TestObject) => obj.name === value); } printValues():void { console.log('strValue',this.strValue); console.log('objValue1',this.objValue1); console.log('objValue2',this.objValue2); console.log('objValue3',this.objValue3); } } 解决方法
我不知道alpha中的内容是什么样的,但我现在正在使用beta 12,这样可以正常工作.如果您有一个对象数组,请创建一个如下所示的选择:
<select [(ngModel)]="simpleValue"> // value is a string or number <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option> </select> 如果你想匹配实际的对象,我会这样做: <select [(ngModel)]="objValue"> // value is an object <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option> </select> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |