Angular 5: select 元素上的 ngModel 绑定不更新
Angular 5: ngModel binding on select element doesn't update
我有一个 select 元素的标记:
<select type="submit" ([ngModel])="selectedValue" #item (change)="onSelectItem(item.value)">
<option>Pick an option</option>
<option *ngFor="let object of objects">{{ object.value }}</option>
</select>
当我从打字稿更新 ngModel 绑定时,没有任何反应。本质上我只是在组件中这样做:
ngOnInit() {
this.selectedValue = 'something' // One of the options from the list of objects
}
然而,没有任何反应。
我试图将其更新为的值在对象列表中(在 *ngFor 中)- 如果重要的话。
将([ngModel])="selectedValue"
更改为[(ngModel)]="selectedValue"
就像docs说的那样:
Visualize a banana in a box to remember that the parentheses go inside the brackets.
此外,如果您使用 ngModel
,则不需要 (change)
侦听器。您可以将双向绑定拆分为 [ngModel]
和 (ngModelChange)
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<select type="submit" [ngModel]="selectedValue" (ngModelChange)="onSelectedChange($event)">
<option *ngFor="let option of options">{{ option }}</option>
</select>
{{ selectedValue }}
` ,
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedValue = 1;
options = [1,2,3]
onSelectedChange(value: number) {
// do something else with the value
console.log(value);
// remember to update the selectedValue
this.selectedValue = value;
}
}
Please change the definition of ([ngModel])
to [(ngModel)]
and you should initialize the objects
values before assign the value in selectedValue
object
我有一个 select 元素的标记:
<select type="submit" ([ngModel])="selectedValue" #item (change)="onSelectItem(item.value)">
<option>Pick an option</option>
<option *ngFor="let object of objects">{{ object.value }}</option>
</select>
当我从打字稿更新 ngModel 绑定时,没有任何反应。本质上我只是在组件中这样做:
ngOnInit() {
this.selectedValue = 'something' // One of the options from the list of objects
}
然而,没有任何反应。 我试图将其更新为的值在对象列表中(在 *ngFor 中)- 如果重要的话。
将([ngModel])="selectedValue"
更改为[(ngModel)]="selectedValue"
就像docs说的那样:
Visualize a banana in a box to remember that the parentheses go inside the brackets.
此外,如果您使用 ngModel
,则不需要 (change)
侦听器。您可以将双向绑定拆分为 [ngModel]
和 (ngModelChange)
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<select type="submit" [ngModel]="selectedValue" (ngModelChange)="onSelectedChange($event)">
<option *ngFor="let option of options">{{ option }}</option>
</select>
{{ selectedValue }}
` ,
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedValue = 1;
options = [1,2,3]
onSelectedChange(value: number) {
// do something else with the value
console.log(value);
// remember to update the selectedValue
this.selectedValue = value;
}
}
Please change the definition of
([ngModel])
to[(ngModel)]
and you should initialize theobjects
values before assign the value inselectedValue
object