我是angular2的新手。我需要在模板加载/初始化时调用函数。我知道如何在angular1.x中执行此操作,但是我无法找出如何在angular-2中完成此操作。

这就是我在angular1.x中尝试过的方式

在html中

<div ng-init="getItems()">
//some logic to get my items
</div>

在 Controller 中
getItems = function(){
console.log('in the getitems function call');
//logic to get my items from db/localStorage
}

这就是我在angular1.x中使用ng-init的方式,但是在angular-2中没有ng-init的问题。请在此问题上帮助我。

最佳答案

@Component({
 ...
})
class MyComponent {
  constructor() {
    // when component class instance is created
  }

  ngOnChanges(...) {
    // when inputs are updated
  }

  ngOnInit() {
    // after `ngOnChanges()` was called the first time
  }

  ngAfterViewInit() {
    // after the view was created
  }

  ngAfterContentInit() {
    // after content was projected
  }
}

有关完整列表,请参见https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#hooks-overview

10-07 17:37