如何在“select"在Angular 2中?

我使用的是Angular 2 (TypeScript)。

我想对新选择做一些事情,但我在onChange()中得到的总是最后一个选择。我如何获得新的选择?

<select [(ngModel)]="selectedDevice" (change)="onChange($event)">
<option *ngFor="#i of devices">{{i}}</option>
</select>
onChange($event) {
console.log(this.selectedDevice);
// I want to do something here with the new selectedDevice, but what I
// get here is always the last selection, not the one I just selected.
}
789221 次浏览

你可以通过在选择标记#device上创建一个引用变量来将值传递回组件,并将它传递给更改处理程序onChange($event, device.value)应该有新值

<select [(ng-model)]="selectedDevice" #device (change)="onChange($event, device.value)">
<option *ng-for="#i of devices">\{\{i}}</option>
</select>


onChange($event, deviceValue) {
console.log(deviceValue);
}

如果你不需要双向数据绑定:

<select (change)="onChange($event.target.value)">
<option *ngFor="let i of devices">\{\{i}}</option>
</select>


onChange(deviceValue) {
console.log(deviceValue);
}

对于双向数据绑定,分离事件和属性绑定:

<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2">
<option [value]="i" *ngFor="let i of devices">\{\{i}}</option>
</select>
export class AppComponent {
devices = 'one two three'.split(' ');
selectedDevice = 'two';
onChange(newValue) {
console.log(newValue);
this.selectedDevice = newValue;
// ... do other stuff here ...
}

如果devices是对象数组,则绑定到ngValue而不是value:

<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
<option [ngValue]="i" *ngFor="let i of deviceObjects">\{\{i.name}}</option>
</select>
\{\{selectedDeviceObj | json}}
export class AppComponent {
deviceObjects = [{name: 1}, {name: 2}, {name: 3}];
selectedDeviceObj = this.deviceObjects[1];
onChangeObj(newObj) {
console.log(newObj);
this.selectedDeviceObj = newObj;
// ... do other stuff here ...
}
}

< a href = " http://plnkr.co/edit/VbJUBkqAlS8UPVgh4bqV?p =预览”>恰好< / > -不使用<form>
砰砰作响 -使用<form>并使用新的表单API

我在https://angular.io/docs/ts/latest/guide/forms.html上Angular 2表单教程(TypeScript版本)时遇到了这个问题

选择/选项块不允许通过选择其中一个选项来改变选择的值。

按照Mark Rajcok的建议去做是有效的,尽管我想知道在最初的教程中我是否遗漏了什么内容,或者是否有更新。在任何情况下,补充

onChange(newVal) {
this.model.power = newVal;
}

到HeroFormComponent类中的hero-form.component.ts

而且

(change)="onChange($event.target.value)"

<select>元素中的heroo -form.com component.html使其工作

使用[ngValue]代替[value]!!

export class Organisation {
description: string;
id: string;
name: string;
}
export class ScheduleComponent implements OnInit {
selectedOrg: Organisation;
orgs: Organisation[] = [];


constructor(private organisationService: OrganisationService) {}


get selectedOrgMod() {
return this.selectedOrg;
}


set selectedOrgMod(value) {
this.selectedOrg = value;
}
}




<div class="form-group">
<label for="organisation">Organisation
<select id="organisation" class="form-control" [(ngModel)]="selectedOrgMod" required>
<option *ngFor="let org of orgs" [ngValue]="org">\{\{org.name}}</option>
</select>
</label>
</div>

另一种选择是将对象的value存储为字符串:

<select [ngModel]="selectedDevice | json" (ngModelChange)="onChange($event)">
<option [value]="i | json" *ngFor="let i of devices">\{\{i}}</option>
</select>

组件:

onChange(val) {
this.selectedDevice = JSON.parse(val);
}

这是唯一的方法,我可以得到双向绑定工作,以设置页面加载的选择值。这是因为填充选择框的列表与我的选择绑定的对象不完全相同,它需要是相同的对象,而不仅仅是相同的属性值。

最新的离子3.2.0修改为ionChange

< p >如: HTML < / p >
<ion-select (ionChange)="function($event)"> <ion-option>1<ion-option>
</ion-select>

TS

function($event){
// this gives the selected element
console.log($event);


}
<mat-form-field>
<mat-select placeholder="Vacancies" [(ngModel)]="vacanciesSpinnerSelectedItem.code" (ngModelChange)="spinnerClick1($event)"
[ngModelOptions]="{standalone: true}" required>
<mat-option *ngFor="let spinnerValue of vacanciesSpinnerValues" [value]="spinnerValue?.code">\{\{spinnerValue.description}}</mat-option>
</mat-select>

我使用这个角材质下拉。工作正常

< em >角5 < / em >中,我用下面的方法做了。获取对象event.value美元而不是event.target.value美元

<mat-form-field color="warn">
<mat-select (ngModelChange)="onChangeTown($event)" class="form-width" formControlName="branch" [(ngModel)]="branch" placeholder="Enter branch">
<mat-option *ngFor="let branch of branchs" [value]="branch.value">
\{\{ branch.name }}
</mat-option>
</mat-select>
</mat-form-field>


onChangeTown(event): void {
const selectedTown = event;
console.log('selectedTown: ', selectedTown);
}

使用selectionChange在角6及以上。例子 (selectionChange)= onChange($event.value) < / p >

角7/8

从angular 6开始,在响应式表单指令中使用ngModel input属性已经被弃用并在angular 7+中被完全移除。点击这里阅读官方文件。

使用响应式表单方法,您可以获得/设置选定的数据为;

      //in your template
<select formControlName="person" (change)="onChange($event)"class="form-control">
<option [value]="null" disabled>Choose person</option>
<option *ngFor="let person of persons" [value]="person">
\{\{person.name}}
</option>
</select>




//in your ts
onChange($event) {
let person = this.peopleForm.get("person").value
console.log("selected person--->", person);
// this.peopleForm.get("person").setValue(person.id);
}

在Angular 8中,你可以像这样简单地使用"selectionChange":

 <mat-select  [(value)]="selectedData" (selectionChange)="onChange()" >
<mat-option *ngFor="let i of data" [value]="i.ItemID">
\{\{i.ItemName}}
</mat-option>
</mat-select>

我尝试了所有的建议,但没有一个对我有效。

想象一下这样的情况:您需要一个双向绑定,并且有一个带有NUMBER值的查找,您希望用这个查找的值填充SELECT并突出显示所选的选项。

使用[value]或(ngModelChange)是行不通的,因为在用户发起更改后,你将无法选择所选的选项:[value]认为所有内容都是字符串,至于(ngModelChange)——它显然不应该在用户发起更改时使用,因此它破坏了正确的选择。使用[ngModel]可以保证接收到的价值的固定格式为价值指数:,并且很容易相应地解析它,然而,它再次破坏了所选的选项。

因此,我们使用[ngValue](它将负责正确的类型),(change)和…[value],它保证处理程序接收价值,而不是显示值价值指数::)下面是我的工作笨拙的解决方案:

  <select
class="browser-default custom-select"
(change)="onEdit($event.target.value)"
>
<option [value]="">\{\{
'::Licences:SelectLicence' | abpLocalization
}}</option>
<ng-container *ngIf="licencesLookupData$ | async">
<option
*ngFor="let l of licencesLookupData$ | async"
[ngValue]="l.id"
[value]="l.id"
[selected]="l.id == selected.id"
>
\{\{ l.id }} &nbsp;&nbsp; \{\{ l.displayName | defaultValue }}
</option>
</ng-container>
</select>


onEdit(idString: string) {
const id = Number(idString);
if (isNaN(id)) {
this.onAdd();
return;
}
this.licencesLoading = true;
this.licencesService
.getById(id)
.pipe(finalize(() => (this.licencesLoading = false)), takeUntil(this.destroy))
.subscribe((state: Licences.LicenceWithFlatProperties) => {
this.selected = state;
this.buildForm();
this.get();
});
}

我也有同样的问题,我用下面的代码解决了:

(change)="onChange($event.target.value)"

如果你不需要双向数据绑定:

<select (change)="updateSorting($event)">
<option disabled selected>Sorting</option>
<option value="pointDes">pointDes</option>
<option value="timeDes">timeDes</option>
<option value="timeAsc">timeAsc</option>
<option value="pointAsc">pointAsc</option>
</select>
updateSorting(e: any) {
// console.log((e.target as HTMLSelectElement)?.value); // also work
console.log(e.target.value);
}