Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect change to a property in Angular

Tags:

angular

I have a component with a sub component timeline.

<app-timeline [(editing)]="editingDate"></app-timeline>

In the timeline component I have these properties:

@Input() editing: boolean; // <--- detect change on this
@Output() editingChange = new EventEmitter();

How can I check when a change to the editing property occurs from the timeline component? I need to emit the editing value whenever it changes.

Should I use a setter for the editing property then emit from there?

private _editing
set editing() { ... // emit }

Or is there another way?

like image 848
matt Avatar asked Jan 19 '19 11:01

matt


1 Answers

The ngOnChanges can be used exactly for this

First make sure your component implements the ngOnChanges like this

export class TimelineComponent implements OnChanges

Then implement the ngOnChanges method like this

ngOnChanges(changes: SimpleChanges) {
    if (changes.editing) {
        console.log(changes.editing.currentValue);
    }
}

Any time any input was changed it will enter the ngOnChanges method. This is also why the if statement was added since if any other input was changed the editing property won't exist on the changes object.

For primitive values it will trigger on any change. For reference values you need to change the actual reference, just changing a property of the object you have in the input won't work.

like image 145
Jelle Avatar answered Oct 07 '22 03:10

Jelle