angular监听输入框值的变化_如何在Angular2中检测@Input()值的变化

实际上,当angular2 +中的子组件input发生变化时,有两种方法可以检测和处理:

您可以使用ngOnChanges()生命周期方法 ,也可以在以前的答案中提到:

@Input() categoryId: string; ngOnChanges(changes: SimpleChanges) { this.doSomething(changes.categoryId.currentValue); // You can also use categoryId.previousValue and // categoryId.firstChange for comparing old and new values }

文档链接: ngOnChanges, SimpleChanges, SimpleChange

演示例子:看看这个笨蛋

或者,您也可以使用input属性设置器 ,如下所示:

private _categoryId: string; @Input() set categoryId(value: string) { this._categoryId = value; this.doSomething(this._categoryId); } get categoryId(): string { return this._categoryId; }

文档链接:看这里 。

演示例子:看看这个笨蛋 。

哪种方法应该使用?

如果你的组件有几个input,那么,如果你使用ngOnChanges(),你将在ngOnChanges()中同时获得所有input的所有改变。 使用这种方法,您还可以比较已更改input的当前值和以前的值,并据此采取相应措施。

但是,如果只想在某个特定的input发生变化时执行某些操作(而不关心其他input),那么使用input属性设置器可能会更简单。 但是,这种方法并没有提供内置的方法来比较已更改input的前一个值和当前值(您可以使用ngOnChanges生命周期方法轻松完成此操作)。

编辑2017-07-25:angular度更改检测可能仍然不会在某些情况下火灾

通常, 如果数据是JS原始数据types(string,数字,布尔值),则只要父组件更改传递给子组的数据,setter和ngOnChanges的更改检测就会触发。 但是,在下列情况下,它不会触发,您必须采取额外的行动才能使其正常工作。

如果您正在使用嵌套对象或数组(而不是JS原始数据types)将数据从Parent传递给Child,则更改检测(使用setter或ngchanges)可能不会触发,也正如用户在答复中所述:muetzerich。 对于解决scheme看这里 。

如果你在angular度上下文之外(即,外部)改变数据,则angular度将不知道这些改变。 您可能必须在您的组件中使用ChangeDetectorRef或NgZone来使angular度知道外部变化,从而触发更改检测。 参考这个 。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular的@Input和@Output是用来实现组件之间通信的注解。 @Input用来接收父组件传递过来的数据,而@Output则用来向父组件传递数据。 下面是它们的使用方法: 1. @Input 在子组件使用@Input注解来接收父组件传递的数据。例如: ``` import { Component, Input } from '@angular/core'; @Component({ selector: 'child-component', template: ` <div>{{data}}</div> ` }) export class ChildComponent { @Input() data: string; } ``` 在父组件使用属性绑定的方式将数据传递给子组件。例如: ``` import { Component } from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child-component [data]="myData"></child-component> ` }) export class ParentComponent { myData = 'Hello world'; } ``` 2. @Output 在子组件使用@Output注解来定义一个事件。例如: ``` import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'child-component', template: ` <button (click)="onClick()">Click me</button> ` }) export class ChildComponent { @Output() clicked = new EventEmitter<void>(); onClick() { this.clicked.emit(); } } ``` 在父组件使用事件绑定的方式监听子组件的事件。例如: ``` import { Component } from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child-component (clicked)="onChildClicked()"></child-component> ` }) export class ParentComponent { onChildClicked() { console.log('Child component clicked'); } } ``` 这样就实现了子组件向父组件传递数据的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值