Using $ onChanges vs $ onInit in an angular component

Is there any difference between using Controller1vs Controller2?

angular.module('app', [])
.component('foo', {
    templateUrl: 'foo.html',
    bindings: {
        user: '<',
    },
    controller: Controller1, //Or Controller2
});

function Controller1(){
    this.$onInit = function(){
      this.user = angular.copy(this.user);
    };

    this.$onChanges = function(changes){
      if(changes.user && !changes.user.isFirstChange()){
        this.user = angular.copy(changes.user.currentValue);
      }
    };
}


function Controller2(){
    this.$onChanges = function(changes){
      if(changes.user){
        this.user = angular.copy(changes.user.currentValue);
      }
    };
}

Why should I bother with $onInitwhen I can just do the same in $onChangesand save some lines?

Is this type of initialization better in $onChangesand $onInitbetter for any other initialization?

+4
source share
1 answer

$ OnInit

, ( ). .

$onChanges

$onChanges . -, , , Object , . , , - '<' ( ) "@" ( DOM), . $onChanges Object , , .

$onInit , $onChanges, < @.

0

Source: https://habr.com/ru/post/1666363/


All Articles