简体   繁体   English

我该如何听角度2中的代码更改?

[英]how can I listen to changes in code in angular 2?

I'm using angular 2. I have a component with an input. 我正在使用角度2。我有一个带有输入的组件。 I want to be able to write some code when the input value changes. 我希望能够在输入值更改时编写一些代码。 The binding is working, and if the data is changed (from outside the component) I can see that there is change in the dom. 绑定正在工作,并且如果更改了数据(从组件外部),我可以看到dom中有更改。

@Component({
    selector: 'test'
})
@View({
    template: `
    <div>data.somevalue={{data.somevalue}}</div>`
})
export class MyComponent {

    _data: Data;
    @Input()
    set data(value: Data) {
        this.data = value;
    }
    get data() {
        return this._data;
    }

    constructor() {
    }

    dataChagedListener(param) {
        // listen to changes of _data object and do something...
    }
}

You could use the lifecycle hook ngOnChanges : 您可以使用生命周期挂钩ngOnChanges

export class MyComponent {
  _data: Data;
  @Input()
  set data(value: Data) {
    this.data = value;
  }
  get data() {
    return this._data;
  }

  constructor() {
  }

  ngOnChanges([propName: string]: SimpleChange) {
    // listen to changes of _data object and do something...
  }
}

This hook is triggered when: 在以下情况下触发此挂钩:

if any bindings have changed 如果任何绑定已更改

See these links for more details: 有关更多详细信息,请参见以下链接:

As mentioned in the comments of Thierry Templier's answer , ngOnChanges lifecycle hook can only detect changes to primitives. Thierry Templier的回答评论中所述, ngOnChanges生命周期挂钩只能检测到基元的更改。 I found that by using ngDoCheck instead, you are able to check the state of the object manually to determine if the object's members have changed: 我发现通过改用ngDoCheck ,您可以手动检查对象的状态,以确定对象的成员是否已更改:

A full Plunker can be found here . 完整的柱塞可在此处找到 But here's the important part: 但这是重要的部分:

import { Component, Input } from '@angular/core';

@Component({
    selector: 'listener',
    template: `
        <div style="background-color:#f2f2f2">
            <h3>Listener</h3>
            <p>{{primitive}}</p>
            <p>{{objectOne.foo}}</p>
            <p>{{objectTwo.foo.bar}}</p>

            <ul>
                <li *ngFor="let item of log">{{item}}</li>
            </ul>
        </div>
    `
})
export class ListenerComponent {
    @Input() protected primitive;
    @Input() protected objectOne;
    @Input() protected objectTwo;

    protected currentPrimitive;
    protected currentObjectOne;
    protected currentObjectTwo;

    protected log = ['Started'];

    ngOnInit() {
        this.getCurrentObjectState();
    }

    getCurrentObjectState() {
        this.currentPrimitive = this.primitive;
        this.currentObjectOne = _.clone(this.objectOne);
        this.currentObjectTwoJSON = JSON.stringify(this.objectTwo);
    }

    ngOnChanges() {
        this.log.push('OnChages Fired.')
    }

    ngDoCheck() {
        this.log.push('DoCheck Fired.');

        if (!_.isEqual(this.currentPrimitive, this.primitive)){
            this.log.push('A change in Primitive\'s state has occurred:');
            this.log.push('Primitive\'s new value:' + this.primitive);
        }

        if(!_.isEqual(this.currentObjectOne, this.objectOne)){
            this.log.push('A change in objectOne\'s state has occurred:');
            this.log.push('objectOne.foo\'s new value:' + this.objectOne.foo);
        }

        if(this.currentObjectTwoJSON != JSON.stringify(this.objectTwo)){
            this.log.push('A change in objectTwo\'s state has occurred:');
            this.log.push('objectTwo.foo.bar\'s new value:' + this.objectTwo.foo.bar);
        }

        if(!_.isEqual(this.currentPrimitive, this.primitive) || !_.isEqual(this.currentObjectOne, this.objectOne) || this.currentObjectTwoJSON != JSON.stringify(this.objectTwo)) {
             this.getCurrentObjectState();
        }
    }

It should be noted that the Angular documentation provides this caution about using ngDoCheck : 应该注意的是,Angular文档提供了有关使用ngDoCheck

While the ngDoCheck hook can detect when the hero's name has changed, it has a frightful cost. 尽管ngDoCheck挂钩可以检测到英雄的姓名何时更改,但代价却是惊人的。 This hook is called with enormous frequency — after every change detection cycle no matter where the change occurred. 在每个更改检测周期之后,无论更改发生在何处,都会以极大的频率调用此钩子。 It's called over twenty times in this example before the user can do anything. 在此示例中,它被调用了二十次,用户才能执行任何操作。

Most of these initial checks are triggered by Angular's first rendering of unrelated data elsewhere on the page. 这些初始检查大多数是由Angular在页面其他位置首次呈现无关数据引起的。 Mere mousing into another input box triggers a call. 仅将鼠标悬停在另一个输入框中即可触发呼叫。 Relatively few calls reveal actual changes to pertinent data. 相对而言,很少有电话能揭示出相关数据的实际变化。 Clearly our implementation must be very lightweight or the user experience will suffer. 显然,我们的实现必须非常轻巧,否则用户体验将受到影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何收听角度模板驱动的表单更改 - how to listen of angular template driven form changes 我如何在Angle App中订阅/收听Chrome推送通知 - How can i subscribe/listen to chrome push notifications in angular app 如何在Angular指令中监听元素的属性更改? - How can I listen an element's attribute change in an Angular directive? 如何在 Angular 中侦听组件中的服务变量更改 - How can I listen for a Service variable change in a component in Angular 我们可以在 firestore angular 中监听特定的键值变化吗 - Can we listen specific key value changes in firestore angular 监听对象更新 Angular 的变化 - Listen for changes on object update Angular 如何从类属性TypeScript - Angular中侦听值更改 - How to listen for value changes from class property TypeScript - Angular 如何在不重新加载整个列表的情况下在我的组件 CoinRow 中侦听此变量“编辑”的更改? - How can I listen for changes to this variable 'editing' in my component CoinRow without reload the entire list? 如何监听“道具”的变化 - How to listen for 'props' changes 我可以使用MutationObserver来监听计算样式的变化吗? - Can I use a MutationObserver to listen for changes on computed styles?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM