Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch on complex object in Angular 2 like we did in Angular 1 using $watch

We were able to apply $watch on complex object, how to do the similar in Angular 2.

Angular 1

$scope.data = {name : "somvalue"}
$scope.$watch('data.name', function(newValue, oldValue) {
    scope.counter = scope.counter + 1;
});

Angular 2

export class MyData{
   name: string;
} 

export class MyComponent implements OnInit {
   @Input() data: MyData;

   constructor(private ds: MyService){
      this.data = ds.data;
   }

   // $watch('data.name', function(newValue, oldValue) {
   //   scope.counter = scope.counter + 1;
   // });
}

Now If data.name changes in service, How to watch for the changes in Component itself, Please note data is not an observable it is just a regular object.

Update

Please see Plunk for an example

Thanks in advance!!

like image 929
Madhu Ranjan Avatar asked Jun 17 '16 19:06

Madhu Ranjan


1 Answers

Angular checks properties, even deep inside objects if they are bound to in the template.

For complex objects the preferred option is to use Observable to actively notify Angular2 about changes.

You can also use custom change detection by implementing DoCheck

like image 112
Günter Zöchbauer Avatar answered Nov 09 '22 13:11

Günter Zöchbauer