如何在 Angular 2 中的 "select" 中获得新选择?
How can I get new selection in "select" in 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.
}
您可以通过在 select 标记上创建一个引用变量 #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 ...
}
}
我 运行 在 https://angular.io/docs/ts/latest/guide/forms.html
做 Angular 2 表单教程(TypeScript 版本)时遇到了这个问题
select/option 块不允许通过选择其中一个选项来更改选择的值。
按照 Mark Rajcok 的建议行事,但我想知道我是否在原始教程中遗漏了什么,或者是否有更新。无论如何,添加
onChange(newVal) {
this.model.power = newVal;
}
到 HeroFormComponent 中的 hero-form.component.ts class
和
(change)="onChange($event.target.value)"
<select>
元素中的 hero-form.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>
另一种选择是将值中的对象存储为字符串:
<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);
}
这是我获得双向绑定以在页面加载时设置 select 值的唯一方法。这是因为我填充 select 框的列表与我的 select 绑定到的对象不完全相同,它需要是相同的对象,而不仅仅是相同的 属性 值。
最新的ionic 3.2.0已经修改(更改)为(ionChange)
例如:
HTML
<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>
我将其用于 angular Material 下拉菜单。工作正常
在Angular 5中我是用下面的方法做的。获取对象 $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);
}
在 angular 6 及更高版本中使用 selectionChange。例子
(selectionChange)= onChange($event.value)
Angular 7/8
从 angular 6 开始,使用 ngModel 输入 属性 和反应式表单指令已在 angular 7+ 中完全弃用和删除。 Read official doc here.
使用反应式方法,您可以 get/set 将所选数据作为;
//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) 是不行的,因为在用户启动更改后您将无法 select 选择的选项:[value] 认为一切都是 string,至于 (ngModelChange) - 它显然不应该在用户启动更改时使用,因此它会破坏正确的 selection。使用 [ngModel] 保证接收到的 VALUE 的固定格式为 INDEX: VALUE 并且很容易相应地解析它,但是再一次 - 它破坏了selected 选项。
所以我们使用 [ngValue](它将处理适当的类型)、(更改)和... [value],这保证处理程序接收 VALUE,不是 DISPLAYED VALUE 或 INDEX: 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 }} {{ 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)"
从 angular 7 起,由于 ngModel 已被弃用,我们可以简单地使用控件以反应方式非常轻松地获取新的选定值。
示例:
<form [formGroup]="frmMyForm">
<select class="form-control" formControlName="fieldCtrl">
<option value=""></option>
<option value="val1">label val 1</option>
<option value="val2">label val 2</option>
<option value="val3">label val 3</option>
</select>
</form>
this.frmMyForm.get('fieldCtrl').valueChanges.subscribe( value => {
this.selectedValue = value;
});
通过使用这种完全反应式的方式,我们可以更轻松地将较旧的 angular 应用程序版本升级到较新的版本。
如果不需要two-way data-binding:
<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);
}
我正在使用 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.
}
您可以通过在 select 标记上创建一个引用变量 #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 ...
}
}
我 运行 在 https://angular.io/docs/ts/latest/guide/forms.html
做 Angular 2 表单教程(TypeScript 版本)时遇到了这个问题select/option 块不允许通过选择其中一个选项来更改选择的值。
按照 Mark Rajcok 的建议行事,但我想知道我是否在原始教程中遗漏了什么,或者是否有更新。无论如何,添加
onChange(newVal) {
this.model.power = newVal;
}
到 HeroFormComponent 中的 hero-form.component.ts class
和
(change)="onChange($event.target.value)"
<select>
元素中的 hero-form.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>
另一种选择是将值中的对象存储为字符串:
<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);
}
这是我获得双向绑定以在页面加载时设置 select 值的唯一方法。这是因为我填充 select 框的列表与我的 select 绑定到的对象不完全相同,它需要是相同的对象,而不仅仅是相同的 属性 值。
最新的ionic 3.2.0已经修改(更改)为(ionChange)
例如: HTML
<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>
我将其用于 angular Material 下拉菜单。工作正常
在Angular 5中我是用下面的方法做的。获取对象 $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);
}
在 angular 6 及更高版本中使用 selectionChange。例子
(selectionChange)= onChange($event.value)
Angular 7/8
从 angular 6 开始,使用 ngModel 输入 属性 和反应式表单指令已在 angular 7+ 中完全弃用和删除。 Read official doc here.
使用反应式方法,您可以 get/set 将所选数据作为;
//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) 是不行的,因为在用户启动更改后您将无法 select 选择的选项:[value] 认为一切都是 string,至于 (ngModelChange) - 它显然不应该在用户启动更改时使用,因此它会破坏正确的 selection。使用 [ngModel] 保证接收到的 VALUE 的固定格式为 INDEX: VALUE 并且很容易相应地解析它,但是再一次 - 它破坏了selected 选项。
所以我们使用 [ngValue](它将处理适当的类型)、(更改)和... [value],这保证处理程序接收 VALUE,不是 DISPLAYED VALUE 或 INDEX: 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 }} {{ 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)"
从 angular 7 起,由于 ngModel 已被弃用,我们可以简单地使用控件以反应方式非常轻松地获取新的选定值。
示例:
<form [formGroup]="frmMyForm">
<select class="form-control" formControlName="fieldCtrl">
<option value=""></option>
<option value="val1">label val 1</option>
<option value="val2">label val 2</option>
<option value="val3">label val 3</option>
</select>
</form>
this.frmMyForm.get('fieldCtrl').valueChanges.subscribe( value => {
this.selectedValue = value;
});
通过使用这种完全反应式的方式,我们可以更轻松地将较旧的 angular 应用程序版本升级到较新的版本。
如果不需要two-way data-binding:
<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);
}