Angular 2 中的 OnChange 等效项
Angular 事件绑定是响应任何 DOM 事件的好方法。它们允许我们将代码与元素的原生点击或输入事件绑定,并在它们发生时执行。
OnChanges
可用于监视 Angular 项目中输入参数的变化,我们可以将 Angular 2 中的 OnChanges
等效用于输入字段、按钮单击、列表项,甚至本文将讨论的滚动事件.
Angular 2 中的 OnChange
属性
Angular 2.0 有双向数据绑定。对输入字段的任何更改都将立即反映在 UI 上,反之亦然。
Onchange
是 Angular 2 中输入元素的一个属性,它指定当用户输入它或从下拉列表中选择一个值时应该发生什么。
语法:
ngOnChanges(changes: SimpleChanges)
参数 SimpleChanges
被传递给方法 ngOnChanges()
,该方法在修改后返回新的和以前的输入值。
当使用输入用户对象数据类型时,ngOnChanges()
仅在父组件中对象的链接更改时调用。
如果我们仅仅改变输入用户对象的属性值,ngOnChanges()
方法将不会执行。
Angular 2 中的 OnChange
等价物
OnChanges
事件是一个生命周期钩子,当输入值更改时执行。ngModel
指令将输入或 textarea
元素绑定到当前范围内的属性,并替换了 Angular 2 支持的 HTML5 onchange
事件。
ngModelChange
事件在模型更新并且其值更改时触发。它可以通过将表达式传递给 ngModel
指令或将其绑定到输入来触发。
示例代码 - HTML:
<div>
<input [value]="first" (change)="changeFn($event)">
<p>{{ first }}</p>
<input [ngModel]="second" (ngModelChange)="modelChangeFn($event)">
<p>{{ second }}</p>
</div>
示例代码 - TypeScript:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
first = '1';
second = '2';
changeFn(abc) {
this.first = abc.target.value;
}
modelChangeFn(abc: string) {
this.second = abc;
}
}
输出:
changeFn()
只会在用户模糊输入时执行。另一方面,当用户输入、粘贴或编辑输入值时,ModelChangeFn()
会监听事件并设置对象。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。