问题描述
Angular 1 不接受 onchange()
事件,它只接受 ng-change()
事件.
Angular 1 does not accept onchange()
event, it's only accepts ng-change()
event.
另一方面,Angular 2 接受 (change)
和 (ngModelChange)
事件,这两者似乎都在做同样的事情.
Angular 2, on the other hand, accepts both (change)
and (ngModelChange)
events, which both seems to be doing the same thing.
有什么区别?
哪一种最适合性能?
ngModelChange:
<input type="text" pInputText class="ui-widget ui-text"
(ngModelChange)="clearFilter()" placeholder="Find"/>
vs 变化:
<input type="text" pInputText class="ui-widget ui-text"
(change)="clearFilter()" placeholder="Find"/>
推荐答案
(change)
绑定到经典输入更改事件的事件.
(change)
event bound to classical input change event.
https://developer.mozilla.org/en-US/文档/Web/事件/更改
即使您的输入中没有模型,您也可以使用 (change) 事件
You can use (change) event even if you don't have a model at your input as
<input (change)="somethingChanged()">
(ngModelChange)
是 ngModel 指令的 @Output
.当模型改变时它会触发.如果没有 ngModel 指令,您将无法使用此事件.
(ngModelChange)
is the @Output
of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124
当您在源代码中发现更多内容时,(ngModelChange)
会发出新值.
As you discover more in the source code, (ngModelChange)
emits the new value.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169
所以这意味着你有这样的使用能力:
So it means you have ability of such usage:
<input (ngModelChange)="modelChanged($event)">
modelChanged(newObj) {
// do something with new value
}
基本上,两者之间似乎没有太大区别,但是当您使用 [ngValue]
时,ngModel
事件获得了强大的力量.
Basically, it seems like there is no big difference between two, but ngModel
events gains the power when you use [ngValue]
.
<select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
<option *ngFor="let currentData of allData" [ngValue]="currentData">
{{data.name}}
</option>
</select>
dataChanged(newObj) {
// here comes the object as parameter
}
假设你在没有ngModel
things"的情况下尝试同样的事情
assume you try the same thing without "ngModel
things"
<select (change)="changed($event)">
<option *ngFor="let currentData of allData" [value]="currentData.id">
{{data.name}}
</option>
</select>
changed(e){
// event comes as parameter, you'll have to find selectedData manually
// by using e.target.data
}
这篇关于(change) vs (ngModelChange) 角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!