How to make `ngOnChanges` work in `angular2`

Viewed 73913

My child component as following:

'use strict';

import {Component, Input, OnInit, OnChanges, ChangeDetectionStrategy, ElementRef} from 'angular2/core';

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'my-app',
    template: ''
})
export class MyApp implements OnInit {

    @Input() options: any;

    constructor(private el: ElementRef) {
    }

    ngOnInit() {

    }

    ngOnChanges(...args: any[]) {
        console.log('changing', args);
    }

}

And Parent component as following:

'use strict';

import {Component, Input} from 'angular2/core';
import {MyApp} from './MyApp';

@Component({
    selector: 'map-presentation',
    template: `<my-app [options]="opts"></my-app>
    <button (click)="updates($event)">UPDATES</button>
    `,
    directives: [MyApp]
})
export class MainApp {

    opts: any;

    constructor() {
        this.opts = {
            width: 500,
            height: 600
        };
    }

    updates() {
        console.log('before changes');
        this.opts = {
            name: 'nanfeng'
        };
    }

}

Each time while i clicked the "UPDATES" button, the ngOnChanges method never be called, but why?

I angular version i am using is "2.0.0-beta.8"

3 Answers

Looks like you haven't implemented interface OnChanges ..if you implement OnChanges interface then only ngOnChanges will be consider as lifecycle hook function and it will get call on input changes otherwise it will be consider as normal function

Related